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

我们还可以为其添加取消的功能。

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); } } throttled.cancel = () => { clearTimeout(timer); timer = null; previous = 0; } return throttled; }

此时一个功能完备的throttle函数也完成了。

总结

防抖和节流是两个在工作中很可能会遇到的问题,弄清楚其作用和原理对技能提升和面试都会有帮助。

参考

JavaScript专题之跟着 underscore 学防抖

欢迎到前端学习打卡群一起学习~516913974

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

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