JavaScript function throttling Concept and usage example detailed _javascript skill

Source: Internet
Author: User
Tags set time time interval

This article illustrates the concept and usage of JavaScript function throttling. Share to everyone for your reference, specific as follows:

Recently in the Web page when there is a need, is the browser window changes need to change some of the page element size, it is natural to think of the window resize events, so I wrote the

<! DOCTYPE html>
 
 

The function is implemented, but I drag the way to change the size of the browser window when I looked down the console

Yes, a simple drag to get my Resizehandler () method executed 52 times, which is not exactly what I wanted, and in fact my Resizehandler () method code is very complex, and even uses Ajax to send requests to the server, If it's a simple change of window size, call it 52 times.

function throttling

In fact, my intention is only window resize after the page to make some adjustments can be, and the window resize event is not in the end of the resize triggered, the specific is not a frequency I do not know, but it is in constant call until the window size no longer change. In fact, similar mechanisms and the mousemove of the mouse, are repeatedly triggered in a short period of time.

In JavaScript advanced programming, there is a function throttling to deal with this problem

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

The principle is simple, using the timer, let the function execution delay 500 milliseconds, in 500 milliseconds if there is a function is called to delete the last call, this call after 500 milliseconds to execute, so reciprocating. So the code I just had can be changed to

<script type= "Text/javascript" >
n=0;
function Resizehandler () {Console.log () (
  new Date (). GetTime ());
  Console.log (++n);
}
Function Throttle (method,context) {
  cleartimeout (method.tid);
  Method.tid=settimeout (function () {
    method.call (context);
  },500);
}
Window.onresize=function () {
  throttle (Resizehandler,window);
};
</script>

Drag and drop to try, really only executed once

A different approach

There's also a function throttling scheme on the web, and it does this.

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


Call a try, the same effect

<script type= "Text/javascript" >
n=0;
function Resizehandler () {Console.log () (
  new Date (). GetTime ());
  Console.log (++n);
}
Function Throttle (method,delay) {
  var timer=null;
  return function () {
    var context=this, args=arguments;
    Cleartimeout (timer);
    Timer=settimeout (function () {
      method.apply (Context,args);
    },delay);
  }
Window.onresize=throttle (resizehandler,500);//Because the function handle is returned without wrapping the function
</script>

Comparison

Both methods use SetTimeout, and the second method adds a function that delays execution time, which is easy to have in the first scenario, plus a parameter.

But the first scenario sets the TID as a variable for the function, while the second creates a closure to store. Personally think the gap is small, very like the first, simple, efficient.

New requirements

One day I did a similar thing, like Baidu home page input automatic prompts the same thing, I bound KeyUp event in the text, each time the keyboard bouncing automatically prompts, but do not want to prompt so frequently, so I used the above method, but the tragedy, only to stop typing and so on 500 milliseconds will be prompted, There is no hint at all in the input process. Look at the code, is not it, as long as the user will be blind, in 500 milliseconds to click the keyboard, the prompt function will continue to be delayed, so that only when the pause will prompt, this is meaningless.

Can you do this once in a fixed time interval based on the function throttling?

Small changes

It's on the Internet. We can make some changes to the second method (the first one to expand multiple variables for the function) and to add a parameter as to a fixed interval that must be performed

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);
    }
}}

So every time we judge how long interval, if more than the set time to execute immediately, with just the example to try the effect

Window.onresize=throttle (resizehandler,100,200);

If it's not executed frequently, it's not final.

More readers interested in JavaScript-related content can view the site topics: "JavaScript switching effects and tips summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and tips summary", " JavaScript error and debugging skills Summary, JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and skills summary and JavaScript mathematical calculation usage Summary

I hope this article will help you with JavaScript programming.

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.