Detailed explanation of js anti-shake debounce and throttling throttling
0. Foreword
Anti-shake and throttling are an essential part of our front-end performance optimization, and they are also frequently asked questions in interviews. This article will start from the concept of anti-shake throttling, to the code analysis of the specific implementation, and describe step by step how to implement anti-shake throttling.
1. Anti-shake (debounce)
1.1 Concept
The so-called anti-shake means that after an event is triggered, the function can only be executed once within n seconds. If an event is triggered again within n seconds, the function execution time will be recalculated.
1.2 Implementation ideas
Idea: Start a timer after the event is triggered. If the event is triggered again within the time limit of the timer, clear the timer, write a timer, and trigger when the timer expires.
function debounce(fn, t=500){
let timer;
return function(){
// 如果有定时器,先清除
if(timer) clearTimeout(timer);
// 开启定时器
timer = setTimeout(()=> {
fn.apply(this, arguments);
}, t)
}
}
2. Throttle
2.1 Concept
The so-called throttling refers to triggering events continuously but only executing a function once in n seconds.
2.2 Implementation ideas
Idea: We can design a function that is opened periodically like a control valve. When an event is triggered, let the function execute once, then close the valve, and then open the valve after a period of time to trigger the event again.
function throttle(fn, t=500) {
let startTime = 0;
return function() {
let now = Date.now();
if(now - startTime >= t) {
fn();
startTime = now;
}
}
}
3. Summary
- Anti-shake and throttling are the same:
Both anti-shake and throttling are designed to prevent high-frequency triggering of operations, thereby wasting performance.
- The difference between anti-shake and throttling:
Anti-shake means that after a high-frequency event is triggered, the function will only be executed once within n seconds. If the high-frequency event is triggered again within n seconds, the time will be recalculated. Applicable to scenarios that can be triggered multiple times but the trigger only takes effect the last time.
Throttling is triggered by high-frequency events, but it will only be executed once in n seconds. If the function is triggered multiple times in n seconds, only one will take effect. Throttling will dilute the execution frequency of the function.
- scenes to be used
Anti-shake : search association words in the input box, log in, click the button to submit the form...
throttling : scroll sliding event, resize browser window change event, mousemove mouse movement event, document editing is automatically saved after a period of time...