Questions from "How to dilute scroll events"

Source: Internet
Author: User

Background: I raised a question in Segmentfault How to dilute onscroll , the problem is as follows:

Ask this question during an interview:
The interviewer asks a top navigation bar to scroll to a location, and after that, she goes on to ask how many times a rolling onscroll will be executed and how to dilute it? To make sure she was saying "dilution," I asked her to repeat it, and the solution I gave was to use a variable to make it self-increment when the event was handled, to determine the actual event by reaching a certain size:

var i = 0; //cumulative variable window.onscroll = function () {i++; if (I%500==0) { //perform the actual event}}            
  • She is not satisfied, ask how to finally release this variable?
  • ...
  • then she said, "I want the number of times the onscroll is diluted, not the number of executions (the actual events I mean). "
  • I am very puzzled, the mouse a scroll to trigger this event, how can reduce its number of executions, how to dilute it? is dynamic binding/unbinding an event, and how does it work?

There are no related types of problems found on the Internet, this problem is not a normal level of face test? If not, please give the solution, thank you first.

The first answer that this is the function of throttling, suddenly dawned, na for the answer, this is my first contact with the noun, this thought ended, did not expect to attract a large wave of programmer's eyeball.

Basically, the two ways of using throttle and debounce are indicated:

Throttle(: Throttle valve): is the meaning of function throttling, the frequency of control function calls, fixed time interval execution, that is, continuous calls, regardless of frequency, only fixed time interval (or greater than the time, when the frequency is lower) to execute once, not the problem of "dilution."

debounce(translation: Anti-bounce?) ): Just to shake the meaning, idle control, in a certain idle time interval of the call is not implemented, a simple implementation of the following:

1 varTimer =NULL;2Document.addeventlistener (' MouseMove ',function () {3         if(timer) {4 cleartimeout (timer)5         }6Timer = SetTimeout (function(){7Console.log ("MouseMove");8}, 100);9     }Ten);

The main response to the high frequency of calls, 100 of the meaning is not 100ms execution once, but when the call interval is not more than 100ms, that is, the mouse movement speed is too fast, console.log () will not be executed, unless the moving interval is greater than 100ms, with netizens bumfod , "function throttling allows a function to stop only after you've been triggered, and you're running too fast and it's ignoring you directly." ", not" dilution "in the question.

In conclusion, it is true that both throttle and debounce are able to solve the performance problem, the dilution of the business logic is the number of executions , but not the problem required, then I think this problem is a bit far-fetched, because regardless, whether there is no explicit definition of scroll event, the browser will trigger the scroll event, the difference is there is no callback, there is nothing to execute.

If you want to "reduce the number of executions of scroll", here is a user code that coincides with me, through the settimeout, to perform a time delay rebinding event listener, this method of dilution is the number of times the callback is executed :

1 varCB = {2Onscroll:function() {3Console.log ("scrolling");4Window.removeeventlistener ("Scroll", Cb.onscroll,false);//Remove Event listener here5SetTimeout (function() {6Console.log ("Done");7Window.addeventlistener ("Scroll", Cb.onscroll,false);8}, 200);//Rebind Event Listener after 200ms9   }Ten }; OneWindow.addeventlistener ("Scroll", Cb.onscroll,false);

Students also lead to blocking rendering, affecting the page UI response and other issues,

Other:

Framework Auxiliary _debounce(debounce function in underscore.js)

1 /**2 * [debounce description]3 * @param {[type]} Func [callback function]4 * @param {[type]} wait [length of wait]5 * @param {[Type]} immediate [whether to execute immediately]6 * @return {[type]} [description]7  */8_.debounce =function(func, wait, immediate) {9     varTimeout, args, context, timestamp, result;Ten  One     varlater =function() { A         varLast = _.now ()-timestamp; -  -         //less than wait time, continue to delay wait-last execution later, know last >= wait to execute func the         if(Last < wait && last > 0) { -Timeout = SetTimeout (later, wait-Last ); -}Else { -Timeout =NULL; +             if(!immediate) { -result =func.apply (context, args); +  A                 if(!timeout) context = args =NULL; at             } -         } -     }; -  -     return function() { -Context = This; inargs =arguments; -timestamp =_.now (); to         //whether to execute immediately +         varCallnow = Immediate &&!timeout; -  the         if(!timeout) Timeout =SetTimeout (later, wait); *  $         if(callnow) {Panax Notoginsengresult =func.apply (context, args); -context = args =NULL; the         } +  A         returnresult; the     }; +};
Underscore.js's Debounce

Typeahead Throttle realize the source code:

1Throttle:function(func, wait) {2     varcontext, args, timeout, result, previous, later;3Previous = 0;4later =function() {5Previous =NewDate ();6Timeout =NULL;7result =func.apply (context, args);8     };9     return function() {Ten         varnow =NewDate (), OneRemaining = wait-(now-previous); AContext = This; -args =arguments; -         if(Remaining <= 0) {//if the time is greater than the interval (wait) the cleartimeout (timeout); -Timeout =NULL; -Previous =Now ; -result =func.apply (context, args); +}Else if(!timeout) {//less than, delayed call later -Timeout =SetTimeout (later, remaining); +         } A         returnresult; at     }; -},
Typeahead.js's Throttle

If there is a mistake, please point out the common progress, thank you ^_^

Questions from "How to dilute scroll events"

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.