understand
Both throttling fountion and debouncing Fountion serve the same purpose: to reduce the number of methods invoked and to improve your site’s productivity. Used to handle events that are triggered frequently, such as keyDown, KeyUp, Click, mousemove, resize, etc.
Throttling founction
For example, if you’re eating melon seeds, every time you drop the shells on the floor, the robot will sweep the floor. The robot sweeps back every 10 minutes to the area where you dropped the shells. When it’s done, it leaves, probably to clean the kitchen. At this point, no matter how many melon shells you continue to throw, the robot will not come until after 10 minutes. The throttling function is executed only once in a specified period of time.
The sample
Realize the function of monitoring window changes
Code implementation
var previous = 0;
var timeId;
var throttle = function (callback, interval) {
var now = new Date(a);if (now - previous > interval) {
// Wait until the current cycle ends before executing the commandcallback(); previous = now; }};// Another way to implement throttling
var throttle2 = function (callback, interval) {
// If a scheduled task is set, then nothing needs to be done
if (timeId) {
return;
}
// After a period, set the scheduled task again
timeId = setTimeout(() = > {
callback();
// setTimeout After the timing method is complete, set timeId to undefined
timeId = undefined;
}, interval);
};
Copy the code
Debouncing Fountion
You’re still eating the seeds, but this time it’s your mom sweeping the floor. She tells you to call her when you’re done with the bag of seeds, and she’ll take her time and help you clean it up. No matter how many times you called her before, she heard you, but she didn’t want to talk to you. The anti-shake function will wait for the end of the event, cooling down for a period of ·x time, before it is executed.
The sample
Implement the following search functions based on user input
Code implementation
<body>
<input type="text" id="search-input" />
<p>input event fired times:<span id="fired-times"></span></p>
<p>
debounce search founcion execute times:<span id="debounce-times"></span>
</p>
</body>
Copy the code
var timerId;
const handleUserInput = function () {
var firedTimesDom = document.getElementById("fired-times");
firedTimes = firedTimesDom.innerHTML || 0; // Get the initial fire times
firedTimesDom.innerHTML = parseInt(firedTimes) + 1; // fire times + 1
debounce(callSearchApi, 300);
};
var debounce = function (callback, delay) {
if (timerId) {
clearTimeout(timerId); // It will not be called if it is always requested
}
timerId = setTimeout(callback, delay); // Wait for some time after the request is complete
};
const callSearchApi = function () {
var debounceSearchTimesDom = document.getElementById("debounce-times");
debounceSearchTimes = debounceSearchTimesDom.innerHTML || 0; // Get the initial debounce search times
debounceSearchTimesDom.innerHTML = parseInt(debounceSearchTimes) + 1; // debounce search times + 1
};
const inputBox = document.getElementById("search-input");
inputBox.addEventListener("input", handleUserInput); // input Adds listening events
Copy the code
conclusion
The function name | The difference between | Applicable scenario |
---|---|---|
Throttling function | No matter how many times the event is triggered, it only executes periodically, with no latency | This is useful when you only care about the final state, such as the input search function, which waits for the user to stop typing to get the pre-typed search results |
Image stabilization function | Delay execution at the end of the event | This is useful when you need to know all the intermediate states. For example, tracking the screen width when the user resizes the window and rearranging the page content when it changes, rather than waiting until the user is done |