What’s anti-vibration and throttling?
Anti-shake and throttling are two optimizations for frequent triggering events in web pages.
Image stabilizationdebounce
As the name implies, shake prevention is to prevent jitter, to avoid the repeated triggering of events. Application Scenarios:
- Click button event, the user’s click event within a certain period of time. In order to prevent multiple interactions with the server, we can adopt anti-shake.
- Automatic save event for input box
- The browser
resize
The event
In a word, shaking prevention can be summarized as the function will only be executed once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within N seconds, the time will be recalculated. Based on the above concepts, we can try to implement an anti-shake function:
function debounce(fun,wait){
let timer;
return (. args) = >{
if (timer){
clearTimeout(timer);
}
timer = setTimeout(() = >{ fun(... args); },wait) } }window.onresize = debounce(() = >{
console.log(1);
},1000);
// The console prints 1 only once when the page resizes frequently
Copy the code
The throttlethrottle
Again, throttling is about reducing traffic, reducing the number of events that are frequently triggered and performing them at regular intervals. That is, control how often events fire. Application Scenarios:
scroll
Events that are triggered every once in a while during the scrolling process. (visibleHow to realize lazy loading of picturesThe application of
Throttling can be summarized as a high frequency event firing, but is executed only once in n seconds, and throttling dilutes the execution frequency of the function. Based on the above concepts, we can try implementing a throttling function:
// Use interval implementation
function throttle1(fun,wait){
let time1 = 0;
return (. args) = >{
const time2 = Date.now()
const timeInterval = time2 - time1;
if ( timeInterval < wait){
return
}else{ time1 = time2; fun(... args); }}}window.onresize = throttle1(() = >{
console.log(1);
},1000);
// The console prints every second when pages are resized frequently
// Use timer implementation
function throttle2(fun,wait){
let timer;
return (. args) = >{
if (timer){
return
}else {
timer = setTimeout(() = >{
timer = null; fun(... args); },wait); }}}window.onresize = throttle2(() = >{
console.log(1);
},1000);
// The console prints every second when pages are resized frequently
Copy the code
Conclusion:
If the high-frequency event is triggered again within n seconds, time throttling will be recalculated. If the high-frequency event is triggered again within n seconds, time throttling will be executed only once within n seconds, diluting the execution frequency of the function