throttle 节流
在一定的时间范围内只执行一次
const throttle = function(fn, delay) {
let previous = 0;
let timer = null;
return function run(... args) {
const now = new Date();
const remaining = delay - (now - previous);
//间隔时间超过delay则立马执行
//remaining > delay指的是客户端修改了时间,导致remianing > delay也会立马执行
if (remaining < 0 || remaining > delay) {
previous = now;
fn.call(this, args);
} else if (!timer) {
timer = setTimeout(() => {
previous = new Date();
clearTimeout(timer);
timer = null;
fn.call(this, args);
}, remaining);
}
};
};
debounce防抖
在一定时间内若重复操作,则重新计算开始时间
function debounce(fn, delay) {
let previous = 0;
let timer = null;
return function proxy(...args) {
if (!timer) {
timer = setTimeout(() => {
previous = new Date();
clearTimeout(timer);
timer = null;
fn.call(this, args)
},delay);
}
}
}