On the basic knowledge of JavaScript function Throttling _

Source: Internet
Author: User
Tags time interval

Some of the calculations and processing in browsers are much more expensive than others. For example, DOM operations require more memory and CPU time than non-dom interactions. Successive attempts to do too much DOM-related operations may cause the browser to hang and sometimes even crash. Especially when using the OnResize event handler in IE, it is easy to happen, when the browser size is resized, the event is triggered continuously. If you try to perform a DOM operation inside a onresize event handler, its high frequency changes may cause the browser to crash.

The basic idea behind function throttling is that some code cannot be repeated continuously without interruption. The first time you call a function, you create a timer that runs the code after a specified interval. When the function is called the second time, it clears the previous timer and sets another. If the previous timer had been executed, the operation would have no meaning. However, if the previous timer has not yet been executed, it is actually replacing it with a new timer. The intent is to execute the function only after it has been stopped for a period of time.

 Function throttle (method, context) {
        cleartimeout (method.tid);
        Method.tid = settimeout (function () {
           method.call (context);
         }
     

Application Examples:
Suppose that a <div/> element needs to keep its height equal to the width, and can encode the following:

 function Resizediv () {
        var div = document.getElementById ("mydiv");
        Div.style.height = div.offsetwidth + "px";
      }
      Window.onresize = function () {
        throttle (resizediv);
      }

Here, the resizing function is put into a separate function called Resizediv, and then the OnResize event handler calls Throttle () and passes in the RESIZEDIV function instead of calling Resizediv () directly. In most cases, the user does not feel the change, although the savings to the browser can be very large.

The following is the supplement of other netizens

Today we mainly write about the functions we need in our daily work. Maybe some friends are not aware of the function throttling. In fact, in the work, many scenes need us to do JS throttling. The most common is the screen telescopic resize, as well as events such as Touchmove or scroll. People do not know whether to read the article I wrote before! jquery to judge the page scroll roll down, touchmove sliding direction, when you use these examples, you will find that the page is constantly triggering touchmove or scroll because there is no redrawing of the page, therefore, I'm not using JavaScript function throttling here. However, when we use window.onresize, it will also keep triggering resize events! This is related to the redrawing of the page. Therefore, in the window of the resize, we recommend the use of function throttling way!

Introduction to JavaScript function throttling
If you feel a big lump of text on my head, it doesn't matter, I am here to give a simple example to illustrate the function of throttling bar! For example, when we use

 $ (window). Resize (function () {
      console.log ("haorooms window Resize");
    })

Will find:

This will be exported several times. We simply narrow the window, will continue to trigger!

Such a lot of time in the Div, the page is constantly redrawing, if you encounter a lower version of IE and so on, it is likely that the browser crash phenomenon! In order to avoid this situation, we can use the method of function throttling. The basic idea is this: the first time we call a function, we create a timer, run the code after the specified time interval, and the second time, we clear the previous timer and reset one. If the previous timer has been executed, then this operation is not intentional, if the timer has not been executed, it will be replaced with a new timer. The goal is to execute the function after it has been stopped for some time.

You can write the following in the form of an object:

var haoroomstest={
      Timeoutid:null,
      performprocessing:function () {        
          console.log ("resize");
      Process:function () {
        cleartimeout (this.timeoutid);
        var that=this;
        This.timeoutid=settimeout (function () {
          that.performprocessing ();
        },500)
      }
    }

After that, we'll use:

$ (window). Resize (function () {haoroomstest.process ();})

This will reduce the request, reduce the DOM redraw, to achieve the purpose of throttling!

function throttling Other way
In addition to our use of the object of the way, online and data also introduced on the function of throttling other ways and means, I have a brief introduction to the following several!

function Way One

Function Throttle (method,context) {
      cleartimeout (method.tid);
      Method.tid=settimeout (function () {
        method.call (context);
      },100);
    }

We use the following

function Resizediv () {
      console.log ("Haorooms")
    }

    $ (window). Resize (function () {
      throttle ( RESIZEDIV)
    })

And the above object to achieve the same effect!

function Mode Two

There is a more popular online throttling mode, I write here!

Function Throttle (method,delay) {
      var timer=null;
      return function () {
        var context=this, args=arguments;
        Cleartimeout (timer);
        Timer=settimeout (function () {
          method.apply (Context,args);
        },delay);
      }
    

And then you can write this:

function Resizediv () {
      console.log ("Haorooms")
    }

   window.onresize=throttle (resizediv,500);

New requirements

When we do fuzzy Search Intelligent Association prompts, we will bind the KeyUp event on the input. But I do not want to trigger so often, in the way there will be problems. Therefore, the above function is based on a slight change, as follows:

Function Throttle (method,delay,duration) {
      var timer=null, begin=new Date ();
      return function () {
        var context=this, args=arguments, Current=new Date ();;
        Cleartimeout (timer);
        if (current-begin>=duration) {
           method.apply (Context,args);
           begin=current;
        } else{
          timer=settimeout (function () {
            method.apply (Context,args);
          },delay);
        }
}}

This trigger will not be as frequent as before!

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.