Handle Heavy operations

Source: Internet
Author: User

In some dynamic operations, we do not need to constantly call a function to complete some functions, such as the number of words in the input, we do not have to enter a variable statistics once, but can be counted at a time, such as scroll scrolling events, if we just need to know the distance of scrolling, There is no need to listen to scroll events in real time and listen to them once in a while.

Here we introduce a function that can solve this problem. The code is as follows:

1 //returns a function that, if it is called uninterrupted, will not be executed. 2 //The function is called again after it has stopped calling N milliseconds to be executed. 3 //If there is a pass ' immediate ' argument, the function is immediately scheduled to the execution queue without delay. 4 functionDebounce (func, wait, immediate) {5     vartimeout;6     return function() {7         varContext = This, args =arguments;8         varlater =function() {9Timeout =NULL;Ten             if(!immediate) { One func.apply (context, args); A             }  -         };  -         varCallnow = Immediate &&!timeout; the cleartimeout (timeout); -Timeout =SetTimeout (later, wait); -         if(callnow) { - func.apply (context, args); +         } -     }; + }; A //usage at varMYEFFICIENTFN = Debounce (function() { - //all heavy-duty operation -Console.log (123); -}, 250); -  -Window.addeventlistener (' scroll ', MYEFFICIENTFN);
Where the MYEFFICIENTFN function writes the function of listening scroll

Handle Heavy operations

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.