Stabilization debounce
Callbacks that limit events to multiple executions in a short period of time have the effect of “merging” multiple events into a single response.
- Scenario: Listen to the change event in the input box and give input suggestions
- Stabilization: The change event triggers the callback function until the user enters an end or pauses for a certain amount of time
/ * * * *@param Fn event triggers the callback function *@param Delay Delay time */
function debounce(fn, delay = 500) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() = > {
// Execute the event callback function
fn.apply(this.arguments);
// Clear the timer after execution
timer = null
}, delay)
}
}
/ / call
let elem = document.getElementById('input');
elem.addEventListener('change', debounce(function () {
console.log('change');
}, 1000))
Copy the code
Throttling throttle
After the event’s callback function is executed once, the function stops working for a specified period of time before it can be called again. For events that can be triggered by a large number of events in a short period of time, the response is limited to a certain frequency (interval specified).
- Scenario: Dragging and dropping elements requires constantly retrieving the element’s location and listening for drag events
- Throttling: No matter how fast the drag event is triggered, the callback function is executed at a certain frequency, depending on the time limit
/ * * * *@param Fn event triggers the callback function *@param Delay Delay time */
function throttle(fn, delay = 100) {
let timer = null;
return function () {
if (timer) {
return
}
timer = setTimeout(() = > {
// Execute the event callback function
fn.apply(this.arguments);
// Clear the timer after execution
timer = null
}, delay)
}
}
/ / call
let dom = document.getElementById('div');
dom.addEventListener('drag', throttle(function () {
console.log('drag');
}, 300));
Copy the code