JS Magic Hall: Function Throttle (throttle) and function shake (debounce)

Source: Internet
Author: User

First, preface

The following scenarios are often triggered by frequent events, so frequent DOM operations, resource loading, and other heavy behaviors can cause UI pauses and even browser crashes.

1. Resize, scroll events for window objects

2. MouseMove event when dragging

3. MouseDown, KeyDown events in shooting games

4. Text input, auto-complete KeyUp event

In fact, for the Resize event of window, most of the actual demand is to stop changing the size of n milliseconds after the subsequent processing, while most of the other events are required to perform subsequent processing at a certain frequency. In response to these two needs, there are two solutions for debounce and throttle.

Second, what is Debounce

1. Definition

If you hold a spring with your finger, it will not bounce until you let go.

This means that the action will not be executed until the action is called N milliseconds, and the execution time will be recalculated if the action is called within that n milliseconds.

   Interface Definition :

/* * * Idle time must be greater than or equal to idle,action for idle control return function to execute * @param   idle {Number}    Idle time, in milliseconds * @param action {function}  request association function, actual application needs to be called functions * @return {function}    returns the client call function  */ Debounce (idle,action)

2. Simple implementation

var debounce = function (idle, action) {  var last ;   return function () {    varThis, args = arguments;    Cleartimeout (last);    last = SetTimeout (function () {        action.apply (ctx, args);    }, Idle)   ;};};

Third, what is throttle

1. Definition

If you tighten the faucet until the water is flowing in the form of drops, you will find that every once in a while, there will be a drop.

That is to say pre-set an execution period, when the call action time is greater than or equal to the execution period then the action is executed, and then into the next new cycle.

Interface Definition:

/* * * Frequency control the action execution frequency is limited to sub/delay* @param delay  When return function is called continuously {Number}    Delay time, in milliseconds * @param action {function}  request association function, actual application needs to be called functions * @return {function}    returns the client call function  */ Throttle (Delay,action)

2. Simple implementation

var throttle = function (delay, action) {  var0;   return function () {    var curr = +new  Date ();     if (Curr-last > delay)      action.apply (this, arguments);     = curr;  };};

Four, underscore v1.7.0 related source code analysis

1. _.throttle function

_.throttle =function (func, wait, options) {/*the default value of the options * indicates that Func is called immediately when the return value method is first called, otherwise only the current moment is logged, and Func is called when the second call has a time interval greater than wait.     * Options.leading = true;     * indicates that when the method is called, the time interval specified by wait is not reached, the start timer delay invokes the Func function, and if subsequent calls to the return value method are not reached at the time interval specified by wait and the Func function is not invoked, the called request is discarded.      * Options.trailing = true; * Note: When options.trailing = False, the effect is the same as the simple implementation above*/    varcontext, args, result; varTimeout =NULL; varPrevious =0; if(!options) options = {}; varlater =function () {Previous= Options.leading = = =false?0: _.now (); Timeout=NULL; Result=func.apply (context, args); if(!timeout) context = args =NULL;    }; returnfunction () {varnow =_.now (); if(!previous && options.leading = = =false) Previous =Now ; //Calculate remaining time      varRemaining = wait-(now-previous); Context= This; Args=arguments; //The func function is called when the time interval specified by the wait is reached//supposedly remaining <= 0 is enough to prove that the time interval has arrived for wait, as for remaining > Wait, I'm not sure      if(Remaining <=0|| Remaining >wait) {        //because SetTimeout has a minimum time accuracy problem, there is a time interval to arrive at wait, but the previously set settimeout operation has not been executed yet, so for the sake of insurance, the settimeout operation is cleared first .        if(timeout) {cleartimeout (timeout); Timeout=NULL; } Previous=Now ; Result=func.apply (context, args); if(!timeout) context = args =NULL; } Else if(!timeout && options.trailing!==false) {        //Options.trailing=true, time-lapse execution of the Func functionTimeout =SetTimeout (later, remaining); }      returnresult;  }; };
   Remaining <= 0 is arguably a sufficient proof of the time interval for the wait, and I am not sure what remaining > wait is.

 2. _.debounce function

_.debounce =function (func, wait, immediate) {//immediate default to False    varTimeout, args, context, timestamp, result; varlater =function () {//when the function returned by _.debounce is called multiple times during the time interval specified by wait, the value of timestamp is constantly updated, resulting in last < wait && >= 0 being true, This keeps starting the new timer delay execution Func      varLast = _.now ()-timestamp; if(Last < wait && last >=0) {Timeout= SetTimeout (later, wait-Last ); } Else{Timeout=NULL; if(!immediate) {Result=func.apply (context, args); if(!timeout) context = args =NULL;    }      }    }; returnfunction () {context= This; Args=arguments; Timestamp=_.now (); //when the method is first called and immediate is true, the Func function is called      varCallnow = Immediate &&!timeout; //The first call to the method within the time interval specified by wait invokes the Func function when the timer is started      if(!timeout) Timeout =SetTimeout (later, wait); if(callnow) {result=func.apply (context, args); Context= args =NULL; }      returnresult;  }; };

_.debounce implementation of the wonderful place I think is to use a recursive start timer instead of calling Cleartimeout to adjust the call to the Func function delay execution.

V. Summary

Both throttle and debounce are ways to improve the performance of event handlers by reducing the execution of actual logic processing, and do not substantially reduce the number of triggering events. It is quite easy to confuse the two in concept understanding, and it will be better to combine the specific implementation of each JS library to understand the effect.

Respect the original, reprint please specify from: http://www.cnblogs.com/fsjohnhuang/p/4147810.html ^_^ fat son John

Vi. references

http://www.alloyteam.com/2012/11/javascript-throttle/

Http://www.cnblogs.com/ambar/archive/2011/10/08/throttle-and-debounce.html

JS Magic Hall: Function Throttle (throttle) and function shake (debounce)

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.