Stabilization
Anti-shake shake to prevent hand shake
is to trigger multiple events within a certain period of time, and only the last one is executed.
For example, Baidu Search Association, will only associate the last character entered
Function resizeEvent (content) {
Console.log(`window`+content)
}
Let event = debounce(resizeEvent, 500)
Function debounce(func, delay) {
Let timeOut = null
Return (args) => {
If (timeOut !== null) {
// Clear the last timer and re-clock
clearTimeout(timeOut)
}
timeOut = setTimeout(() => {
Func(args)
}, delay)
}
}
// Trigger event when resizing the browser window
addEventListener(‘resize‘, ()=>{event(1)})
Application:
1.search Lenovo, when users continue to enter values, save the request resources, to ensure that Lenovo is correct
2.window Resize event, anti-Shake lets it trigger only once
Throttling
Triggers multiple events over a period of time, and the function executes once after each interval.
For example, the FPS game has been pressing the mouse, submachine gun bullets at a certain speed bursts
Function resizeEvent (content) {
Console.log(`window`+content)
}
Let event = throttle(resizeEvent, 500)
Function throttle(func, delay) {
Let last = null
Let deferTimer = null
Return (args) => {
Let now = new Date().getTime()
If (last && now < last + delay) {
// The interval is not cleared, the timer is cleared.
clearTimeout(deferTimer)
deferTimer = setTimeout(()=> {
// Re-create the timer, wait for the interval to set the last, execute the function
Last = now
Func(args)
}, delay)
} else {
// the first time or the interval has been exceeded
Last = now
Func(args)
}
}
}
// Trigger event when resizing the browser window
addEventListener(‘resize‘, ()=>{event(1)})
Application:
1. The mouse is constantly clicked to trigger a function, MouseDown (only once per unit of time)
2. The mouse is constantly moving to trigger a function, MouseMove (only triggered once per unit of time)
Summarize
Stabilization and throttling
The same points are intended to solve the performance problems caused by a large number of triggering of a function in a short time.
Different points are based on different business requirements, the principle of implementation is different.
There are problems to discuss together, welcome to the public number of small Qin notes
Anti-shake and throttling for JavaScript functions