Previously written but do not remember where, today colleagues want a slide to the bottom of the page to load more content effect, and think of this thing, it is very practical and commonly used, I would like to remember.
Function throttling literally means the number of times to save a function, and the main idea is to implement the timer blocking function continuously, especially for frequent operations such as window resize and scroll events.
Window's default scroll event interval of about more than 10 milliseconds, if frequent scroll, then go to request, and then render, the performance certainly has a great impact.
Approximate mode:
varProcessor ={timer:NULL, performprocessing:function(){ //the code to execute}, Process:function() {cleartimeout ( This. Timer); This. timer= SetTimeout (function() {processor.performprocessing (); }, 100); } }; //calledProcessor.process ();
performprocessing is a function to be executed frequently, each time the process will erase the previous timer timer. In short, it is performprocessing each time will delay 100ms execution, if in this period of time is executed, each time will be the front of the clear off, to ensure that the 100ms will only be executed once.
Impress function throttling implemented by closures:
function Throttle (FN, delay) { varnull; return function () { varThis, args = arguments; Cleartimeout (timer); = SetTimeout (function () { fn.apply (context, args); }, delay); };
Each of the two methods have advantages and disadvantages, the advantage of the previous package function in the context variable as a function parameter, directly can be customized to execute the function of this variable; the latter function has the advantage of taking the delay time as a variable.
Give me a chestnut:
<! DOCTYPE html>N=0; functionResizehandler () {Console.log (++N); } functionThrottle (method,delay) {varTimer=NULL; return function(){ varcontext= This, args=arguments; Cleartimeout (timer); Timer=settimeout (function() {method.apply (Context,args); },delay); }} window.onresize=throttle (resizehandler,500);//because the function handle is returned, no wrapper function is used.</script></body>Function Throttle Upgrade Version
varThrottleV2 =function(FN, delay, mustrundelay) {varTimer =NULL; varT_start; return function(){ varContext = This, args = arguments, T_curr = +NewDate (); 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); } }; };
Window. OnResize = throttleV2(myFunc, N, + );
The role of the upgrade is Myfun interval 50ms execution once, 100ms must be executed, because it is possible that you myfun in 50ms, this time the timer will be clear off, it will cause the event will never be executed, this is more extreme situation.
Another talk on JavaScript function throttling