上一篇文章写了写对于防抖的货色,与之相干的节流当然也要来聊一聊。
在固定工夫内,屡次触发只执行一次。
相似于定时执行的概念,显然通过setTimeout或者工夫戳都能够实现。
setTimeout
利用setTimeout延时执行的个性,能够在定时器执行的时候去执行事件。
function throttle(func, wait) { let timer; return function(...args) { if (!timer) { timer = setTimeout(() => { func.apply(this, args); timer = null; }, wait); } };}
工夫戳
工夫戳的形式就没啥好说的了,就是计时。
function throttle(func, wait) { let prev = 0; return function(...args) { const now = +new Date(); if (now - prev > wait) { func.apply(this, args); prev = now; } }}
如果常常应用lodash的同学,可能会晓得在lodash的throttle函数中有一个options能够用来配置是否立刻执行、是否在进行之后再触发一次。
再回来看一下下面的两种实现形式:
- setTimeout:进行之后会再触发一次
- 工夫戳:立刻执行
那是不是能够把下面两个交融一下再加上配置,就能够了呢。
最终版
function throttle(func, wait = 0, options = {}) { const { leading, trailing } = options; // leading 是否立刻执行 // trailing 是否在进行之后再执行一次 let timer; let previous = leading ? 0 : +new Date(); const callFunc = (context, args) => { func.apply(context, args); previous = +new Date(); timer = null; } const throttled = function(...args) { const now = +new Date(); // 如果leading是false,那剩余时间则是wait(第一次触发事件时) // 如果leading是true,那剩余时间则是wait-now < 0 const remaining = wait - (now - previous); if (remaining <= 0) { if (timer) { clearTimeout(timer); } // 如果remianing <= 0,则阐明间隔时间大于了wait秒,则执行事件 callFunc(this, args); } else if (!timer && trailing) { // 如果还有剩余时间,则将本轮wait秒完结时应该执行的事件挂载到计时器上 // 这只是为了保障在进行之后的最初一次能执行 timer = setTimeout(() => { callFunc(this, args); }, remaining); } } // 勾销 throttled.cancel = function() { timer && clearTimeout(timer); timer = null; previous = 0; }; // 是否在pending状态 throttled.pending = function() { return !!timer || (+new Date() - previous <= wait); } return throttled;}
相干:
JavaScript日常学习之防抖
JavaScript日常学习之节流
上述代码的残缺代码