First of all, throttling and anti-shake are used to continuously trigger events , such as the onscroll event. If you do not set throttling and anti-shake, when you bind the onscroll event and set the event processing function, you will execute more than n when you slide the scroll wheel. The second event processing function causes performance loss. Throttling and anti-shake are sometimes applied to the input keydown event. Choose throttling or anti-shake according to the specific situation.
Let me briefly explain the concepts of throttling and anti-shake.
-
Throttling : When you keep triggering an event, execute the code you want to execute at regular intervals. (In order to prevent frequent triggering of events and execute code n times)
-
Anti-shake : The event processing function is executed only once the event is not triggered in a fixed time interval after the trigger event is stopped. ( That is, when you continue to trigger an event, only the last code is executed )
(If the event is triggered again within a fixed time interval, the time will be recalculated.) -
Throttling code
var flag = true //节流阀默认为true
window.onscroll = function () {
//触发事件后代码执行第一次
if (flag === false) return // 节流阀闭合则不执行
flag = false // 来到这里即开关打开状态,现在关掉开关以免重复执行
console.log('执行一次')
setTimeout(() => {
//为防止频繁触发,用延迟器来设置时间间隔
flag = true //0.5秒后打开开关
}, 500) //若事件被极频繁触发,也能保证至少等待0.5秒再执行下一次
//的事件处理函数
}
- Anti-shake code
var timer = null //准备一个timer变量来操作定时器
window.onscroll = function () {
clearInterval(timer) //触发事件就清除掉已有定时器
//保证了一定时间间隔内只执行一次事件处理函数
//而这个时间间隔就是下边延时器的500ms
timer = setTimeout(() => {
//设置延时器
console.log('触发')
}, 500) //0.5秒内不触发该事件,则执行一次延时器内代码
}