1、防抖、节流
// 截流与防抖
/**
* @desc 防抖
* @param {number} delay 延迟时间
* @param {func} cb 回调
*/
export function debounce(delay,cb) {
let timeoutID;
function wrapper() {
const self = this;
const args = arguments;
function exec() {
cb.apply(self, args);
}
clearTimeout(timeoutID);
timeoutID = setTimeout(exec, delay);
}
return wrapper;
}
/**
* @desc 截流
* @param {number} delay 延迟时间
* @param {func} cb 回调
*/
export function throttle(delay,cb){
let timeoutID;
let lastExec = 0;
function wrapper() {
const self = this;
const args = arguments;
const elapsed = Number(new Date()) - lastExec;
function exec() {
lastExec = Number(new Date());
cb.apply(self, args);
}
clearTimeout(timeoutID);
if (elapsed > delay) {
exec();
} else {
timeoutID = setTimeout(exec, delay - elapsed);
}
}
return wrapper;
}