防抖(相当于回城效果,只执行最后一次)
function debounce(fn, time) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(context, args);
}, time);
};
}
const debouncedFn = debounce(function() {
console.log('Function is called after 1000ms of last trigger');
}, 1000);
debouncedFn();
debouncedFn();
debouncedFn();
节流(相当于使用技能,等冷却,冷却期间点击技能没有用)
function throttle(fn,time) {
let timer = 0;
return function(){
const context = this
const args = arguments
const now = Date.now()
if(now-timer>=time){
fn.apply(context,args)
timer = now
}
}
}