Understanding the dithering function in JavaScript

Source: Internet
Author: User
Tags event listener

What is a dithering function? We need to understand this concept before learning JavaScript to shake the function. Many people confuse the concept of shaking with throttling, but these two concepts are well understood.

The Debounce function is a function that can limit the frequency of the specified function firing. We can understand that to call the same function more than once, only to get the result of executing the function once, but again at some time, it is possible to regain new results, depending on our settings. What are the application scenarios for this function?

For example, we write a DOM event listener function,

Window.onscroll = function () {    console.log (' Got it! ');}

  

Now when we slide the mouse wheel, we can see that the event is triggered. But we can see that when we roll the mouse wheel, our console is constantly printing messages because the scroll event of window is constantly being triggered by us.

In the current scenario, this may be a harmless behavior, but it can be predicted that when our event listener function (Handler) involves some complex operations (such as AJAX requests, Dom rendering, large amounts of data calculations), it will have a much greater impact on computer performance. , in some older models or in the lower version of the browser (especially IE), it is likely to lead to the occurrence of the freezing situation. So this time we're going to do something. In the specified time period, only a certain number of event handler functions are executed.

Understanding the Chattering function

Said some concepts and application scenarios, but still very awkward, in the end what is the function of shaking?

We can use the following examples to understand:

Suppose you have the following code:

var debounce = function (callback, delay, immediate) {    var timeout, result;    return function () {        var callnow;        if (timeout)            cleartimeout (timeout);        Callnow =!timeout && immediate;        if (callnow) {            result = Callback.apply (this, Array.prototype.slice.call (arguments, 0));            Timeout = {};        }        else {            timeout = setTimeout (() =>{                callback.apply (this, Array.prototype.slice.call (arguments, 0));            } , delay);};};    var s = debounce (() =>{    console.log (' yes ... ');}, +); window.onscroll = s;

  

The Debounce function is a simple dithering function that I implement, and we can experiment with this code.

The steps are as follows:

    • Copy the above code, open the browser, open the console (F12), then paste the code and enter the execution.
    • Continuously scroll the mouse to see if the console has any output.
    • Stop scrolling the mouse and scroll the mouse again within 2s to see if there is an output.
    • Stop over 2s after continuous scrolling to see if there is an output.

Through the above steps, we can find that when we roll the mouse continuously, the console no message is printed out, stop within 2s and scroll again, there is no message output, but when we stop more than 2s, we can see the console has a message output.

This is the chattering function. In a continuous trigger (no matter how long), only the effect of triggering one time is obtained. Triggers continuously for a specified length of time, with a maximum of one trigger effect.

The realization of underscore

The underscore source code is as follows (with codes comments):

Returns a function, that, as long as it continues to be invoked, would not//be triggered. The function would be called after it stops being called for//N milliseconds. If ' immediate ' is passed, trigger the function on the//leading edge, instead of the trailing.//de-jitter function, the incoming function executes after the wait time (or before) , and will only be executed once. If immediate is passed as true, it is called immediately when the function is passed. Implementation principle: Involves asynchronous JavaScript, multiple calls to the function returned by _.debounce, will be executed one time, but each call//This function will also empty the last timeoutid, so actually only the final settimeout of the content. _.debounce = function (func, wait, immediate) {var timeout, Result;var later = function (context, args) {timeout = null;// If the args parameter is not passed, then Func does not execute. if (args) result = func.apply (context, args);};/ /function returned, the function will only be called once. var debounced = Restargs (args) {//This line of code is to clear the last timeoutid,//so that if there are multiple calls to the function's scene, only the delay of the final call is performed. if (timeout) cleartimeout (timeout), if (immediate) {////If immediate is passed and timeout is empty, then Func is called immediately, otherwise it is not called immediately. var Callnow =!timeout;//The following line of code, the Func function inside the later function is not destined to be executed because no arguments are passed to the later. Its role is to ensure that a timeout is returned. Timeout = SetTimeout (later, wait); if (Callnow)result = Func.apply (this, args);} else {//If immediate is not passed, the _.delay function is used to delay execution of later. Timeout = _.delay (later, wait, this, args);} return result;}); /This function is used to cancel the current shake-out effect. Debounced.cancel = function () {cleartimeout (timeout); timeout = null;}; return debounced;};

  

You can see that underscore uses a closure method that defines two private properties: timeout and result, and two private methods later and debounced. Eventually, Debounced is returned as a function after processing. Timeout is used to accept and store settimeout returned by the Timeoutid,result used to perform the execution of the user-passed Func function, and the later method is used to execute the incoming Func function.

Implementation principle

Using JavaScript's asynchronous execution mechanism, JavaScript takes precedence over all synchronization code and then goes to the event queue to perform all asynchronous tasks.

When we constantly trigger the debounced function, it will continue to cleartimeout (timeout) and then reset the new timeout, so we actually reset the timeout before each call to the debounced function until our synchronization code finishes executing. Therefore, the asynchronous task in the asynchronous event queue refreshes continuously until the last debounced function finishes executing. Only the later asynchronous task that is set by the last debounced function is executed after the synchronization code executes.

So when we are rolling the mouse in the previous experiment, we are actually constantly calling the debounced function, constantly clearing the asynchronous task of timeout, and then setting up a new timeout asynchronous task. When we stop for no more than 2s, the asynchronous task of timeout has not been triggered, so scrolling the mouse again triggers the debounced function to clear the timeout task and set a new timeout task. Once the stop time exceeds 2s, the asynchronous code corresponding to the final timeout will be executed.

Summarize
    • Shaking is a way to limit the frequency of function execution.
    • The function after shaking is triggered at most once in the specified time, and the function that triggers the chattering continuously only gets the trigger effect once.
    • Underscore the implementation relies on the asynchronous execution mechanism of JavaScript, prioritizes synchronous code execution, and executes asynchronous code in the event queue.
Reference
    • The realization of underscore function shake-out
    • JavaScript debounce Function
    • Stack Overflow:what does _.debounce do?

Read More about underscore Source:GitHub

Understanding the dithering function in JavaScript

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.