Applicable scene
Anti-shake:
- search Search Lenovo, when the user is continuously inputting values, use anti-shake to save request resources
- When the window triggers resize, the continuous adjustment of the browser window size will continuously trigger this event, and use anti-shake to make it only trigger once
Throttling:
- The mouse is clicked continuously to trigger, mousedown (triggered only once per unit time)
- Listen for scrolling events, such as whether to slide to the bottom to automatically load more
the code
Anti-shake:
let timer = null;
function debounce(){
clearTimeout(timer);
timer = null;
timer = setTimeout(()=> {
console.log('防抖成功!')
}, 1000)
}
Throttling:
function throttle(){
let valid = true;
if(valid) {
setTimeout(()=> {
console.log('节流成功!')
valid = true;
}, 1000)
valid = false;
}
}
Summarize:
Both are similar:
Both anti-shake and throttling are designed to prevent high-frequency triggering of operations, thereby wasting performance.
difference between the two
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 the scenario 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.