//=>防抖:每隔wait时间只可以执行一次
function debounce(func, wait, immediate) {
let result = null,
timeout = null;
return function(...args) {
let context = this,
// 如果immediate为true 并且没有其他定时器存在,now为true,会立即执行
now = immediate && !timeout;
//=>只要触发这个函数,先清除一遍定时器,确保每次只有一个定时器在等待
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) result = func.call(context, ...args);
}, wait);
//=>如果now为true,则立即执行函数,由于有定时器的存在,所以下次触发的时候,timeout有值,now的值为false
if (now) result = func.call(context, ...args);
return result;
}
};
//=>节流:假设wait为100,事件触发了2000,那么在这2000时间中,事件会触发20次
function throttle(func, wait) {
let timeout = null,
result = null,
previous = 0; //=>上次执行时间点
return function(...args) {
let now = new Date, //=>获取本地时间
context = this;
//=>remaining小于等于0,表示上次执行至此所间隔时间已经超过一个时间间隔wait
let remaining = wait - (now - previous);
if (remaining <= 0) {
clearTimeout(timeout);
previous = now;
timeout = null;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(() => {
previous = new Date;
timeout = null;
result = func.apply(context, args);
}, remaining);
}
return result;
}
}