function stabilization and throttling [reprint]

Source: Internet
Author: User

Underscore.js provides a number of useful functions, and two functions are used to restrict the execution of a function.

Debounce

Before explaining this function, let's take a look at the usage scenario of this function from an example. Suppose our site has a search box, user input text we will automatically associate to match some results for the user to choose. The first thing we might think of is listening to the KeyPress event and then asynchronously querying the results. The method itself is correct, but if the user quickly entered a series of characters, assuming that it is 10 characters, then will be triggered in an instant 10 times the request, which is certainly not what we want. We want the user to stop the input when the request to trigger the query, this time the function of anti-shake can help us.

The function of anti- shake is to let a function after the last execution, to wait for a certain time to no longer trigger this function before execution, and in this wait time to trigger this function again, wait time will be recalculated.

Let's take a look at the definition of the correlation function in Underscore.js:

_.debounce (function, wait, [immediate])

Returns a function, that, as long as it continues to be invoked, would notBe triggered. The function would be called after it stops being called forN milliseconds. If ' immediate ' is passed, trigger the function on theLeading edge, instead of the trailing._.debounce =function(Func, wait, immediate) {var timeout, args, context, timestamp, result;var later =function() {var last = _.now ()-timestamp;if (Last < wait && last >=0) {timeout = SetTimeout (later, wait-last);}else {timeout = null; if (!immediate) {result = Func.apply (context, args); if (!timeout) context = args = null;}} }; return function () {context = this; args = arguments; timestamp = _ . Now (); var callnow = immediate &&!timeout; if (!timeout) timeout = SetTimeout (later, wait); if (callnow) {result = Func.apply (context, args); context = args =  Null } return result;};           

parameter functions are functions that require a function shake-out, and the parameter wait is the time to wait, in milliseconds, and if the immediate parameter is true, the Debounce function performs a function immediately upon invocation without waiting for the wait time , such as to prevent multiple clicks when clicking the Submit button to use this parameter.

So, the above scenario, we can solve this:

function query() {   //进行异步调用查询 }var lazyQuery = _.debounce(query, 300);$(‘#search‘).keypress(lazyQuery);
Throttle

Our site often has this demand, that is, when scrolling the browser scroll bar, update some layout content on the page or to call the background of an interface query content. Similarly, if the frequency of a function call is not limited, then it is possible for us to scroll the scroll bar to produce n calls. But this time the situation is different from the above, we do not want to execute a function after every waiting time, but to execute a function at some time every interval to avoid too much execution of the function, this way is called function throttling .

Again, let's look at the definition of the correlation function in Underscore.js:

_.throttle (function, wait, [options])

Returns a function, that, when invoked, 'll only is triggered at the most onceDuring a given window of time. Normally, the throttled function would runAs much as it can, without ever going more than once per ' wait ' duration;But if you ' d like to disable the execution on the leading edge, pass' {Leading:false} '. To disable execution on the trailing edge, Ditto._.throttle =function(func, wait, options) {var context, args, result;var timeout =Nullvar previous =0;if (!options) options = {};var later =function() {previous = Options.leading = = = =False?0: _.now (); Timeout =Null result = func.apply (context, args);if (!timeout) context = args =Null };Returnfunction() {var now = _.now ();if (!previous && options.leading = = = false) Previous = Now var remaining = wait-(now-previous); context = this; args = 
                                    
                                     arguments; 
                                     if (remaining <= 0 | | remaining > Wait) {if (timeout) {cleartimeout (timeout); timeout = null;} previous = now; result = Func.apply (context, args); if (!timeout) context = args = null;} else if (!timeout && options.trailing!== false) {timeout = SetTimeout (later, remaining);} return result;};           
                                    

The parameter function is the functions that need to be throttled, and the parameter wait is the time interval of the function execution, in milliseconds. option has two options, the function is executed immediately by default when the first call is throttle, and if the {Leading:false} is passed in, the function is not executed on the first call. The {Trailing:false} parameter represents a call that prohibits the last deferred delay. Concrete can see the source to understand.

So, in the case of rolling scrollbars, we can do this:

function handleScroll() {   //进行滚动时的相关处理 }var throttled = _.throttle(handleScroll, 100);$(window).scroll(throttled);
Reference

http://underscorejs.org/#debounce
http://underscorejs.org/#throttle

Original http://segmentfault.com/a/1190000002764479

function stabilization and throttling [reprint]

Related Article

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.