In the book advanced programming of JavaScript, there is an introduction to function throttling, which encapsulates a function throttle function:
function throttle(method, context) { clearTimeout(methor.tId); method.tId = setTimeout(function(){ method.call(context); }, 100); }
It saves the timer ID as a property of the function. and write it directly when you call it.
window.onresize = function(){ throttle(myFunc);}
Impress is used with another encapsulation function:
var throttle = function(fn, delay){ var timer = null; return function(){ var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function(){ fn.apply(context, args); }, delay); }; };
It uses the method of closure to form a private scope to hold the timer variable timer. Instead, the calling method is
window.onresize = throttle(myFunc, 100);
Both methods have advantages and disadvantages, the advantage of the previous package function is to use context variables as function parameters, directly can be customized to execute the function of the this variable; the latter function has the advantage of taking the delay as a variable (of course, the previous function is easy to do this extension), and personally think that using the closure code structure will be better, and easy to expand custom other private variables, the disadvantage is that although using apply to call throttle when the this context passed to the execution function, but after all, not flexible.
The above-described function throttle, it this frequency is not 50ms and so on, it is infinite, as long as you can uninterrupted resize, brush for a few years it also does not execute the processing function. We can expand on the throttling function above:
var throttleV2 = function(fn, delay, mustRunDelay){ var timer = null; var t_start; return function(){ var context = this, args = arguments, t_curr = +new Date(); clearTimeout(timer); if(!t_start){ t_start = t_curr; } if(t_curr - t_start >= mustRunDelay){ fn.apply(context, args); t_start = t_curr; } else { timer = setTimeout(function(){ fn.apply(context, args); }, delay); } }; };
In this extended throttle function upgrade, we can set the third parameter, that is, the time interval that inevitably triggers execution. If you use the following method to invoke the
window.onresize = throttleV2(myFunc, 50, 100);
This means that the call is triggered continuously within the 50ms interval, and the latter call will be processed by the previous call, but at least once every 100ms. The principle is also very simple, playing time tag, start recording the first time the call timestamp, and then each call function to get the latest time and record time, more than a given time to execute once, update the record time.
JS function Throttle JQuery throttle/debounce