面试之手写防抖节流 (10)

可以看出节流的主要原理就是利用时间差(当前和上次执行)来过滤中间过程触发的函数执行。我们现在为其添加参数来控制是否在开始时会立即触发一次,及最后一次触发是否执行。

function throttle(fn, wait, options = { leading: true, trailing: false }) { let timer; let previous = 0; const { leading, trailing } = options; const throttled = function (...args) { const now = +new Date(); if (leading === false && !previous) previous = now; if (timer) clearTimeout(timer); if (now - previous > wait) { fn.apply(this, args); previous = now; } else if (trailing) { // 更新timer timer = setTimeout(() => { fn.apply(this, args); previous = 0; timer = null; }, wait); } }; return throttled; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsfjds.html