2020-03-12
描述
创建一个受限制的函数,每 wait
毫秒最多只能调用提供的函数一次。
提示
- 使用
setTimeout()
和clearTimeout()
来限制给定的方法fn
- 使用
Function.prototype.apply()
将this
上下文应用到受限函数中,并提供其必要的arguments
- 使用
Date.now()
跟踪上一次调用受限函数的时间 - 第二个参数
wait
用于设置受限函数每次执行的时间间隔,默认值为 0
代码
const throttle = (fn, wait) => { let inThrottle, lastFn, lastTime; return function() { const context = this, args = arguments; if (!inThrottle) { fn.apply(context, args); lastTime = Date.now(); inThrottle = true; } else { clearTimeout(lastFn); lastFn = setTimeout(function() { if (Date.now() - lastTime >= wait) { fn.apply(context, args); lastTime = Date.now(); } }, Math.max(wait - (Date.now() - lastTime), 0)); } }; };
示例
当窗口拖动时,每 250 毫秒内只打印一次窗口的尺寸:
window.addEventListener( 'resize', throttle(function(evt) { console.log(window.innerWidth); console.log(window.innerHeight); }, 250) );
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于