Debounce 防抖
一直点击,一直不触发。
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds.
频繁触发一个事件,绑定的回调函数不会立即执行,只有以最后一次触发的实践开始等待了特定
wait的时长后,才会执行,每一次触发都会清除上一次调用创建的定时器,重新计时。
如下图示:

如下代码:
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds.
* @param {*} fn 需要防抖的函数
* @param {*} wait 下一次触发函数的时间间隔
*/
function debounce(fn, wait) {
let timeout = null;
return function(...args) {
clearTimeout(timeout)
timeout = setTimeout(() => {
fn(...args);
}, wait);
}
}
Throttle 节流
一直点击,按间隔时间触发。
频繁触发一个事件,绑定的函数不会立即执行,只有定时器 wait 的时间到了,才会将 flag 设置为 true, 继续点击时,再等待 wait 时间,再进行触发;若等待的时间不足 wait,就直接 return, 并不会接着触发。
如下图示:

如下代码:
/**
* To throttle a function means to ensure that
* the function is called at most once in
* a specified time period (for instance, once every 10 seconds).
* This means throttling will prevent a function from running
* if it has run “recently”.
* Throttling also ensures a function is run regularly at a fixed rate.
* @param {*} fn 需要节流的函数
* @param {*} wait 函数调用的周期时间
*/
function throttle(fn, wait = 100) {
let flag = false;
// 包装后的节流函数
return function(...args) {
// wait 时间没有到,就不会触发 fn 函数
if (!flag) return;
flag = false;
setTimeout(() => {
fn.call(this, ...args);
flag = true;
}, wait);
}
}
参考文献: