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 );