防抖(debounce)
函数的防抖)指的是, 在持续触发事件时, 当一定时间内没有在触发, 事件处理函数才会执行一次, 如果设定时间到来之前又触发, 则重新延迟.
function debounce(fn, delay) {
let timer;
return function (...args) {
const that = this;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
fn.apply(that, args);
timer = null;
}, delay);
}
}
节流(throttle)
节流指的是, 当持续触发事件时, 保证一定时间段内只调用一次事件处理函数
function throttle(fn, duration) {
let timer = null;
let lasttime = Date.now();
return function (...args) {
const that = this;
const nowtime = Date.now();
const remaining = duration - (nowtime - lasttime);
if (timer) {
clearTimeout(timer);
}
if (remaining <= 0) {
fn.apply(that, args);
lasttime = nowtime;
}
timer = setTimeout(function () {
fn.apply(that, args);
timer = null;
}, remaining);
}
}
网友评论