一定的时间间隔内只触发执行一次,等待当前时间间隔过完才去执行下一个任务
function throttle(fn, interval) {
let flag = true;
return function () {
if (!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this);
flag = true;
}, interval);
};
}
function log() {
console.log(document.documentElement.scrollTop);
}
window.addEventListener('scroll', throttle(log, 2000));
function throttle(fn, interval) {
let start = 0;
return function () {
let now = new Date().getTime();
if (now - start < interval) return;
start = now;
fn.apply(this);
};
}
function log() {
console.log(document.documentElement.scrollTop);
}
window.addEventListener('scroll', throttle(log, 2000));