JS的防抖与节流
防抖(debounce)
// 不需要立即执行的
let t;
$(window).on('scroll', function () {
clearTimeout(t);
t = setTimeout(function () {
console.log(1);
}, 100)
}
})
// 需要立即执行的(改进)
let t;
let flag = true;
$(window).on('scroll', function () {
if (flag) {
// Do someting...
flag = false;
clearTimeout(t);
t = setTimeout(function () {
flag = true;
}, 100)
}
})
节流 (throttle)
/**
* @param fn 方法
* @param wait 间隔时间ms
* @param immediately 是否立刻执行
*/
function throttle(fn: Function, wait: number, immediately: boolean = true) {
let timer = null;
let prev = null;
let exceed = false;
return function() {
let now = new Date().getTime();
if (!prev) prev = now;
if (immediately && !exceed) {
exceed = true;
fn();
return
}
if (now - prev > wait) {
fn();
prev = now;
return
}
clearTimeout(timer);
timer = setTimeout(fn, wait)
}
}