[Concept] JS's function throttling and throttle and debounce detailed

Source: Internet
Author: User
Tags diff

JS's function throttling and throttle and debounce detailed:
Also realizes a function, may have the high efficiency, some efficiency is low, this phenomenon in the high energy dissipation execution process distinguishes is more obvious.
A more common way to improve performance in this section, often called "function throttling," is described in code examples below.
I. What is a function throttle:
In the actual coding, MouseMove and resize are very frequent event types (and of course, other similar event types), such events have a common feature is that in a normal operation, it is possible to execute the event handler function in a very short time, it will greatly loss performance, For example, the Resize event, each execution of the DOM element will usually be recalculated, which is very lossy performance, not to mention the frequent execution, so it is not affected by the effect of the situation as much as possible to reduce the number of event handler execution is very important.
Two. How to throttle the function:
1.throttle mode:
This word has the meaning of "throttling" in English.
More commonly, it is the frequency at which the function executes, and the time interval at which the function is executed twice in succession.
The following code:

[JavaScript]Plain Text view copy code Run code
123456789 var timer=null;$(window).on(‘resize‘,function(){  if(timer){    clearTimeout(timer)  }  timer=setTimeout(function(){    console.log("蚂蚁部落");  },400);});


The code implements the function throttle effect, when the browser window size is resized, the "ant tribe" will not be output, when the adjustment stopped after 400 milliseconds will not output.
The above way does realize the function throttle effect, but feel a bit too harsh, usually we need not when the adjustment is not output, but the output frequency is lower, to achieve such a function, the following will share a piece of code.
2.debounce mode:
This approach is similar to throttle, but its focus is on the time interval of the function call, and the throttle focus is the time interval for function execution.
The debounce mode is very effective for controlling the long press of the keyboard violence input.
Three. Example code:
If the relative function throttling is thoroughly understood, it is best to fully analyze the source code that implements this function.

[JavaScript]Plain Text view copy code Run code
01020304050607080910111213141516171819202122232425262728293031323334353637 var throttle = function (fn,delay, immediate, debounce) {    var curr = +new Date(),  last_call = 0,  last_exec = 0,  timer = null,  diff,  context,  args,  exec = function () {    last_exec = curr;    fn.apply(context, args);  };  return function () {    curr= +new Date();    context = this,    args = arguments,    diff = curr - (debounce ? last_call : last_exec) - delay;    clearTimeout(timer);    if(debounce){      if(!immediate){        timer=setTimeout(exec, delay);      }       else if(diff >= 0){        exec();      }    }     else{      if(diff >= 0){        exec();      }       else if(!immediate){        timer = setTimeout(exec, -diff);      }    }    last_call = curr;  }};


Although the code assigns a function object reference to a variable named throttle, in fact it implements throttle and debounce two ways, as long as the parameters can be adjusted, the following on its implementation of the process to make a comment.
Code Comment:
1.var throttle = function (Fn,delay, immediate, debounce) {}, this function can return an event handler with four parameters, FN is a function object, the throttle is its execution, Delay specifies the time of the deferred execution, in milliseconds, immediate is a Boolean value, and if true, then the correlation function executes immediately, otherwise deferred execution, Debounce is a Boolean value, if true, then the Debounce method is used.
2.var Curr = +new date (), gets the current time, is a timestamp.
3.last_call = 0, declares a variable and initializes it to 0, which is used to store the last time the function was attempted to be called.
4.last_exec = 0, declares a variable and initializes it to 0, which is used to store the last time the function function was executed.
5.timer = null, declares a variable, and initializes null, which stores the identifier of the timer function.
6.diff, used to store the time difference.
7.context, used to store a context object.
8.args, the parameter used to store the function.
9.exec = function () {
Last_exec = Curr;
Fn.apply (context, args);
Declare a function that gets the event that the function executes and executes the FN function passed through the parameter.
The 10.return function () {}, which returns a function, is the event handler function that is constantly being called.
11.curr= +new Date () to get the timestamp of the current time object.
12.context = This, assigning the context to this.
13.args = arguments, assigns a collection of parameter objects to the variable args.
14.diff = Curr-(debounce? last_call:last_exec)-delay, which is a very tricky technique to get the current time and delay time, or the time difference between the last call or execution time.
Cleartimeout (timer), stop the execution of the timer function.
16.if (debounce) {if (!immediate) {
Timer=settimeout (exec, delay);
}
else if (diff >= 0) {
exec ();
}
}
If the Debounce method is used, and the delay is used, then the function is deferred for the specified time, and if there is no delay, and the time difference is greater than or equal to 0 (indicating that the delay has been reached), the function is executed.
17.else{
if (diff >= 0) {
exec ();
}
else if (!immediate) {
Timer = setTimeout (exec,-diff);
}
}
If you are using the throttle method, then you will determine whether the diff is greater than 0, if more than 0 to execute the function, the first execution will certainly be greater than 0, that is, the throttle mode in the first execution of the time will not have a delay effect. If it is not greater than 0, and deferred mode is used, execution is deferred.
Perhaps read the above introduction, the two ways feel more confused, then you can seefunction ThrottlingThrottle and Debounce code demosection so that you can visually observe the difference between the two and the other.

[Concept] JS's function throttling and throttle and debounce detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.