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