A general understanding
Anti-shake and throttling are used to avoid frequent triggering events that cause a large number of computations, which may affect page jitter or even stutter. Anti – shake is triggered after the event is executed in unit time, if triggered again in unit time then the time will be reset. Throttling is performed when triggered, but triggering is no longer performed in unit time.
Stabilization Debounce
The anti-shake timer setTimeOut is used to trigger the event in a unit of time. If it is triggered again in a unit of time, the time will be settled again.
export function Debounce(fn, delay) {
let timer = null;
let self = this;
return (. args) = > {
if (timer){
clearTimeout(timer);
}
timer = setTimeout(() = >{ fn.apply(self, ... args); }, delay) } }Copy the code
Throttling Throttle
Throttling uses timestamps to trigger on execution, but triggers are no longer executed per unit of time.
export function Throttle(fn, delay) {
let last = 0;
let self = this;
return (. args) = >{
if (last == 0 || Date.now() > last) { fn.apply(self, ... args); last =Date.now() + delay; }}}Copy the code
Two, how to use
For example, in vUE
methods:{
handleThrottle: Throttle(function () {
console.log('Throttle'+ Math.random())
},3000),
handleDebounce: Debounce(function () {
console.log('Debounce'+ Math.random())
},3000),
}
Copy the code
Application scenarios
Image stabilization (debounce)
- Search search association, the user in the continuous input value, use the anti – shake to save the request resources.
- Windows triggers resize. Resize the browser window repeatedly to trigger resize. Use stabilization to make it trigger only once
The throttle (throttle)
-
Click the mouse repeatedly to trigger the mousedown(trigger only once per unit of time)
-
Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle