JavascriptThrottle & Debounce _ basic knowledge

Source: Internet
Author: User
Throttle: Ignore all calls within a certain period of time. Debounce: If no call is made at a certain interval, we will introduce the Throttle & amp; Debounce application. If you are interested, refer to the following: Throttle
Ignoring all calls within a certain period of time is suitable for use when the frequency is high and the processing is heavy.

The Code is as follows:


Var throttle = function (func, threshold, alt ){
Var last = Date. now ();
Threshold = threshold || 100;
Return function (){
Var now = Date. now ();
If (now-last <threshold ){
If (alt ){
Alt. apply (this, arguments );
}
Return;
}
Last = now;
Func. apply (this, arguments );
};
};


Debounce
The called method is executed only when no call is made within a certain interval.

The Code is as follows:


Var debounce = function (func, threshold, execASAP ){
Var timeout = null;
Threshold = threshold || 100;
Return function (){
Var self = this;
Var args = arguments;
Var delayed = function (){
If (! ExecASAP ){
Func. apply (self, args );
}
Timeout = null;
};
If (timeout ){
ClearTimeout (timeout );
} Else if (execASAP ){
Func. apply (self, args );
}
Timeout = setTimeout (delayed, threshold );
};
};


Test

The Code is as follows:


Var test = function (wrapper, threshold ){
Var log = function (){
Console. log (Date. now ()-start );
};
Var wrapperedFunc = wrapper (log, threshold );
Var start = Date. now ();
Var arr = [];
For (var I = 0; I <10; I ++ ){
Arr. push (wrapperedFunc );
}
While (I> 0 ){
Var random = Math. random () * 1000;
Console. log ('index: '+ I );
Console. log ('random: '+ random );
SetTimeout (arr [-- I], random );
}
};
Test (debounce, 1000 );
Test (throttle, 1000 );

Related Article

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.