concept
Function debounce: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated.
Function throttling: A high-frequency event fires but only executes once in n seconds, so throttling dilutes the function’s execution frequency.
Both function throttling and debounce are intended to limit the frequency at which functions are executed to optimize for delays, false death, or stuttering if the response time is too high.
For example, the following situation:
Window object resize, Scroll drag event mousemove text input, keyup event automatically completed
Function debounce
Drawback: If the event is repeatedly triggered within a specified time interval, the call method will be continuously delayed
// debounce code:
function debounce(fn,delay) {
var timer = null; // Create a flag to store the return value of the timer
return function () {
// Remove the previous setTimeout whenever the user enters
clearTimeout(timer);
// Then create a new setTimeout to ensure that the fn function will not be executed if the time keeps firing during the interval
timer = setTimeout(() = > {
fn.apply(this.arguments);
}, delay);
};
}
// handle the function
function handle() {
console.log('Anti-shake:'.Math.random());
}
// Scroll events
window.addEventListener('scroll', debounce(handle,500));
Copy the code
Function throttle
Implementation: Each time the event is triggered, if there is a delay function waiting to be executed, return directly
// Throttle code:
function throttle(fn,delay) {
let canRun = true; // Save a tag through a closure
return function () {
// Check whether the flag is true at the beginning of the function, otherwise return
if(! canRun)return;
// Set it to false immediately
canRun = false;
// Place the execution of an external function in setTimeout
setTimeout(() = > {
// Finally, set the flag to true after setTimeout (critical) to indicate that the next loop can be executed.
// The flag is always false when the timer is not executed and is returned at the beginning
fn.apply(this.arguments);
canRun = true;
}, delay);
};
}
function sayHi(e) {
console.log('Throttle:', e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi,500));
Copy the code
The difference between
Can we usually take the elevator as an example to vividly describe the difference between the two function stabilization: if someone into the elevator (trigger), the elevator will set out after 10 seconds (event listener), at this moment if again someone into the elevator (trigger this event again in 10 seconds), we have to wait 10 seconds to start time (again). Function throttling: ensure that if the first person in the elevator, 10 seconds after the punctual delivery, this time from the first person on the elevator timing, no waiting, if there is no one, it will not run.
Function throttling ensures that a true event handler is executed within a specified period of time, no matter how frequently the event is triggered, whereas function stabilization fires only once after the last event. For example, in an infinite load scenario, we want the user to make Ajax requests every once in a while while the page is scrolling, rather than asking for data when the user stops scrolling. This scenario is suitable for throttling technology to achieve.
Function stabilization: Combine multiple operations into one operation. The idea is to maintain a timer that fires after the delay, but if it fires again within the delay, the timer will be cancelled and reset. In this way, only the last operation can be triggered.
Function throttling: causes functions to fire only once in a given period of time. The principle is to determine whether a delayed call function has not been executed.