We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
频繁的事件触发,会消耗很多的资源,甚至出现卡顿现象。解决这个问题一般有防抖(debounce)和节流(throttle)两个方案
只以最后一次触发的时间为准,延迟n秒后才执行。如果延迟n秒的时间内又触发事件,则以新的事件为时间基准,延迟n秒再执行
clearTimeout(timer)
function debounce(func, wait) { var timeout; return function () { clearTimeout(timeout) timeout = setTimeout(func, wait); } }
控制事件发生的频率,如控制为1s发生一次,甚至1分钟发生一次
timer = setTimeout
timer = null
nowTime - lastTime > wait
//1.设置定时器 function throttle(func, wait) { var timeout = null; return function() { if (!timeout) { timeout = setTimeout(function(){ timeout = null; func() }, wait) } } } //2.使用时间戳 function throttle2 (func, wait) { let lastTime = 0; return function () { let nowTime = +new Date(); if (nowTime - lastTime > wait) { func(); lastTime = nowTime } } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
javascript系列之 防抖 (debounce)与节流 (throttle) 篇
频繁的事件触发,会消耗很多的资源,甚至出现卡顿现象。解决这个问题一般有防抖(debounce)和节流(throttle)两个方案
1.防抖 (debounce)
原理:
只以最后一次触发的时间为准,延迟n秒后才执行。如果延迟n秒的时间内又触发事件,则以新的事件为时间基准,延迟n秒再执行
应用场景:
简单代码:防抖重在清零
clearTimeout(timer)
2.节流 (throttle)
原理:
控制事件发生的频率,如控制为1s发生一次,甚至1分钟发生一次
应用场景:
简单代码:节流重在开锁关锁
timer = setTimeout
timer = null
、nowTime - lastTime > wait
The text was updated successfully, but these errors were encountered: