In JS, most of the function calls are triggered by the user's active invocation, but in some events, such as MouseMove, Window.onresize, Touchmove, the number of calls to the function is very frequent, which consumes a large amount of memory space in the browser. Causes the browser to lag or even feign animation question. So the purpose of the function throttling is to reduce the number of calls to the function in these events, which is never controllable.
There are many ways to implement a function throttle, the general principle is to use the settimeout function, deferred execution of the event handler function, before the function is executed, call it again when it is ignored, the concrete implementation is as follows:
/** Throttle Function * The function that actually needs to be called in the FN event * Interval function minimum number of times to call **/varThrottle =function(FN, interval) {var_self = FN, timer,//TimerIsFirst =true;//is it the first time that you call return function(){ varargs =arguments, _this= This; if(IsFirst) {//If this is the first time, do not need to walk the timer_self.apply (_this, args); returnIsFirst =false; } /*from the second execution, we're going to start the timer.*/ if(timer)return;//if the function within the timer has not yet executed a returnTimer = SetTimeout (function(){//Timing Functioncleartimeout (timer); Timer=NULL; _self.apply (_this, args); }, Interval|| 100) }}//TestWindow.onresize = Throttle (function() {Console.log (222);} , 500);
Then you can compare without using the throttle method, you will find that the printing frequency is significantly reduced
Get!!!
JS function throttling