概念:
函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。
函数节流(throttle)与 函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。
防抖:
function debounce(fn, delay=1000) {
let timer = null;
return function() {
const args = arguments,
that = this;
clearTimeout(timer);
timer = setTimeout(()=> {
fn.apply(that, args)
}, delay)
}
}
function test() {
console.log(Math.random())
}
window.addEventListener('scroll', debounce(test, 2000));
节流
function throttle1(fn, delay=200) {
let timer = null;
let lastTime;
return function() {
let args = arguments,
that = this,
nowTime = Date.now();
if (lastTime && nowTime - lastTime < delay) {
clearTimeout(timer);
timer = setTimeout(() => {
lastTime = nowTime;
fn.apply(that, args);
}, delay)
} else {
lastTime = nowTime;
fn.apply(that, args);
}
}
}
//节流throttle代码:
function throttle(fn,delay) {
let canRun = true; // 通过闭包保存一个标记
let timer = null;
return function () {
let args = arguments,
that = this;
// 在函数开头判断标记是否为true,不为true则return
if (!canRun) return;
// 立即设置为false
canRun = false;
clearTimeout(timer);
// 将外部传入的函数的执行放在setTimeout中
timer = setTimeout(() => {
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
// 当定时器没有执行的时候标记永远是false,在开头被return掉
fn.apply(that, args);
canRun = true;
}, delay);
};
}
function test() {
console.log(Date.now())
}
window.addEventListener('scroll', throttle(test, 200));