JS function throttling

Source: Internet
Author: User

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

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.