防抖:触发事件后在n秒内函数只执行一次,如果n秒内又触发了事件,则会重新计算函数执行事件。
只要不断触发某个事件,就不断地把前面的计时器清空,只保留最后一次定时器的执行
function debounce(func, delay) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(function() {
func.apply(context, args);
}, delay)
}
}
节流:连续触发事件但在n秒中只执行一次函数。
如果timer被赋值了,也就是任务还在等待执行,那么暂时不改变timer的值
function throttle(func, delay) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (timer) {
return;
}
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay)
}
}
function throttle(func, delay) {
let pre = 0;
return function() {
let context = this;
let args = arguments;
let now = new Date();
if (now - pre > delay) {
func.apply(context, args);
pre = now;
}
}
}