312 字
2 分钟
js的防抖和节流实现
Random Cover
当需要限制某个函数被频繁调用时,节流(throttling)和防抖(debouncing)是两种常用的技术。
-
节流:限制函数在一定时间间隔内只执行一次。即使在该时间间隔内多次触发函数,也只会执行一次。
-
防抖:延迟函数的执行,在一定时间内只执行一次。如果在该时间内再次触发函数,则重新开始计时。
下面是使用 JavaScript 实现节流和防抖的示例代码:
// 节流函数function throttle(func, delay) { let timeoutId let lastExecTime = 0
return function (...args) { const currentTime = Date.now() if (currentTime - lastExecTime >= delay) { func.apply(this, args) lastExecTime = currentTime } }}
// 防抖函数function debounce(func, delay) { let timeoutId
return function (...args) { clearTimeout(timeoutId) timeoutId = setTimeout(() => { func.apply(this, args) }, delay) }}
// 测试节流函数const throttleFn = throttle(() => { console.log('Throttled function executed')}, 1000)
// 测试防抖函数const debounceFn = debounce(() => { console.log('Debounced function executed')}, 1000)
// 模拟触发函数setInterval(() => { throttleFn() debounceFn()}, 300)在上面的代码中,throttle 函数会确保被限制的函数在一定时间间隔内只执行一次,而 debounce 函数会在一定时间内延迟函数的执行,如果在延迟时间内再次触发函数,则重新计时。
赞助支持
如果这篇文章对你有帮助,欢迎赞助支持!
最后更新于 2024-06-02,距今已过 563 天
部分内容可能已过时
March7th