今天回顾了一下防抖和节流
防抖
防抖就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
防抖类似于王者荣耀回城6秒,如果回城中被打断,再次回城需要再等6秒
实现代码
function debounce(fn, delay) {
var timer = null;
return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay);
}
}
使用方式
function foo() {
console.log('debounce');
}
let debounced = debounce(foo, 500);
window.addEventListener('scroll', debounced);
节流
节流就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率
节流类似王者荣耀技能在3秒能触发一次,触发一次后,3秒能将不能被触发。
实现代码
function throttle(fn, delay) {
let timer = null;
return function() {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
};
}
使用方式
function foo() {
console.log('throttle');
}
let throttled = throttle(foo, 500);
window.addEventListener('scroll', throttled );