If the throttle
Function anti-shake and function throttling: It is mainly a means to optimize the high frequency execution of JS code. Some events in JS, such as browser resize, Scroll, mouse mousemove, mouseover, input input box keypress, will constantly call the callback function bound to the event when triggered, which wastes resources greatly. Reduces front-end performance. To optimize the experience, you need to limit the number of calls to these events.
For example, to go to work in the morning, taking the bus is to prevent trembling, taking the subway is to throttle;
Take the bus is not the same, the driver will wait for the guests are on the bus, make sure that there is no one within a period of time on the bus
Throttling: The subway stops at the station only for a specified time and leaves on arrival
Image stabilization
First of all, the most important thing to do before writing code is to think in your mind what logic this code needs to implement. Here is the logic of the code.
You may trigger the event, but I must be n seconds after the event triggered, if you trigger the event within n seconds of an event triggered, then I will take the time of the new event as the standard, n seconds after the execution, in short, is waiting for you to trigger the event, n seconds no longer trigger the event, I will execute!
function debounce(func, waitTime) {
let timeout;
return function () {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(func, waitTime); }}document.querySelector('#app').onmousemove = debounce(function fn(event){
console.log(this);
console.log(event);
}, 1000);
Copy the code
The little piece of code above, debounce, is the original anti-shock code.
The above code logic is to determine whether there is a timer, there is a clear timer, and then redefine a timer, timer time to execute fn function.
As you can see, the above lines of code use the knowledge of closures. The main purpose is to keep the timeout variable in the local scope after the function is executed and not pollute the global variable.
If you want the timeout variable to remain after the debounce function is finished, you can use closures to place the variable to be saved in the debounce scope and the other statements in the subfunction scope and return it as a function.
There may be a little bit of doubt. Why do I have to return a function here. It’s actually easy to understand, so let’s look at the following code
let timeout;
function debounce(func, waitTime) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(func, waitTime);
}
document.querySelector('#app').onmousemove = debounce(function fn(event){
console.log(this);
console.log(event);
}, 1000);
Copy the code
I deleted the return from debounce and then, to preserve timeout, I put it in the global variable. These lines of code look similar to the above, but you can just run through the code and see that Debounce only executes once!!
In fact, the reason we return a function in debounce is because onMousemove requires an unexecuted function, and our test code will only return undefined after executing once
document.querySelector('#app').onmousemove = debounce(function fn(event){
console.log(this);
console.log(event);
}, 1000);
document.querySelector('#app').onmousemove = undefined;
Copy the code
Of course, events are not properly bound. If you want to make sense of it, you can actually bind it like this
var timeout;
function debounce(func, waitTime) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(func, waitTime);
}
document.querySelector('#app').onmousemove = function(event) {
debounce(function(){
console.log(this);
console.log(event);
}, 1000);
}
Copy the code
This is the same as the first debounce function that returns a function through a closure, and using closures avoids global contamination of the variable.
However, in this version of the code, we print this and event objects in fn and find something wrong.
As we can see from the above figure, this refers to the window, and event is undefined. This result is not expected, so we need to manually pass this and event objects to the fn function. Hence the following second version of the anti – shake function.
function debounce(func, waitTime) {
let timeout;
return function () {
let _this = this,
args = arguments;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () { func.apply(_this, args) }, waitTime); }}Copy the code
This code uses apply to pass this and event objects to fn. If you are not familiar with this problem, you can read this article in detail
The result shown above is what we want, with the element and event value corresponding to the event
The throttle
Let’s move on to the code logic for throttling.
When the event is triggered, we set a timer, and when the event is triggered, if the timer exists, it is not executed until the timer is executed, and then the function is executed to clear the timer so that the next timer can be set.
function throttle(func, waitTime) {
let timeout;
return function() {
let _this = this;
let args = arguments;
if(! timeout) { timeout =setTimeout(function(){
timeout = null;
func.apply(_this, args)
}, waitTime)
}
}
}
Copy the code
Similarities and differences comparison
Similarities:
- Both can be implemented using setTimeout.
- The goal is to reduce the frequency of callbacks. Saves computing resources.
Difference:
- Function chattering focuses on events that are fired continuously for a certain period of time and only execute once last, while function throttling focuses on executing only once in a period of time.
Anti – shake and throttling applications
For utility functions such as stabilization and throttling, we can put them in public files and call them directly where needed.
The core use of anti-shake and throttling is to optimize code performance, which can be used in many ways, such as input field validation, lazy image loading, various DOM events that are frequently triggered, and so on.
Application scenarios of function anti-shake
There are sequential events that only need to trigger a callback once for the scenario
- The search box searches for input. The user only needs to type one last time before sending the request
- Mobile phone number, email verification and so on input detection
- Window size Resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.
Application scenarios of function throttling
The scenarios in which a callback is executed at an interval are:
- Scroll to load, load more or roll bottom to listen
- Google search box, search association function
- Click submit frequently, and the form is submitted repeatedly
reference
Thoroughly understand function tremble and function throttling
JavaScript series – Anti – shake and throttling