use setTimeout to reduce scroll callback frequency

This commit is contained in:
Reorx 2022-04-10 17:47:41 +08:00
parent d50ce4575d
commit d7f6d6a773
1 changed files with 9 additions and 1 deletions

View File

@ -146,7 +146,7 @@ window.addEventListener('DOMContentLoaded', function (event) {
let activeHeading = headings[0];
getLinkByHeading(activeHeading).classList.add(activeClass);
window.addEventListener('scroll', () => {
const onScroll = () => {
const passedHeadings = [];
for (const h of headings) {
// 5 px as a buffer
@ -166,6 +166,14 @@ window.addEventListener('DOMContentLoaded', function (event) {
activeHeading = newActiveHeading;
getLinkByHeading(activeHeading).classList.add(activeClass);
}
}
let timer = null;
window.addEventListener('scroll', () => {
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(onScroll, 50)
}, false);
function getLinkByHeading(heading) {