函数节流
function throttle(fn, delay = 1000, immediate = true) {
let Running = false;
return () => {
if (!Running) {
Running = true;
immediate === false && fn.apply(this, arguments);
setTimeout(() => {
immediate && fn.apply(this, arguments);
Running = false;
}, delay);
}
};
}
用法
function OnClick() {
console.log('Clicked!');
}
let clicked = throttle(OnClick, 1000);
clicked();
//'Clicked!'
clicked();
clicked();
函数防抖
function debounce(fn, delay = 1000) {
let timer = false;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this, arguments);
}, delay);
}
}
用法
function OnClick(){
console.log('Clicked!');
}
let clicked = debounce(OnClick,1000);
clicked();
clicked();
clicked();
//'Clicked!'