Understanding the SetTimeout and setinterval_javascript techniques in JavaScript timers

Source: Internet
Author: User
Tags setinterval time interval

I. Explanatory notes

1. Overview

SetTimeout: Call a function after the specified delay time or execute a code fragment

SetInterval: Periodically invokes a function or executes a piece of code.

2. Grammar

SetTimeout:

var Timeoutid = window.settimeout (func, delay, [param1, Param2, ...]);
var timeoutid = window.settimeout (code, delay);
    • Timeoutid is the numeric ID of the delay operation, which can then be used as a parameter to the Window.cleartimeout method
    • Func is the function you want to perform after delay milliseconds.
    • Code is in the second syntax, which you want to execute after delay milliseconds.
    • Delay is the number of milliseconds to delay (one second equals 1000 milliseconds), and the call to the function occurs after that delay. But the actual delay may be slightly longer.
    • Standard browsers and IE10 support the ability to pass extra parameters to a delay function in the first syntax

SetInterval

var intervalid = Window.setinterval (func, delay[, param1, param2, ...));
var intervalid = window.setinterval (code, delay);
    • Intervalid is the unique identifier for this repeat operation and can be passed as an argument to Clearinterval ().
    • Func is the function you want to call repeatedly.
    • Code is an application of another syntax, a string of strings that you want to execute repeatedly.
    • Delay is the number of milliseconds per delay (one second equals 1000 milliseconds), and each call to the function occurs after that delay. As with settimeout, the actual delay time may be slightly longer.
    • Standard browsers and IE10 support the ability to pass extra parameters to a delay function in the first syntax
<script type= "Text/javascript" >
  settimeout (function (param) {alert (param)}, +, ' OK '); 
</script>

A simple test of the next fifth, on my computer, respectively, using Firefox and IE9 test, the former can be successfully pop-up OK, the latter pop-up undefined.

Second, "This" question

Code that is invoked by SetTimeout () runs on an execution environment that is completely detached from the function in which it is located. This causes the This keyword contained in the code to point to the window (Global object) object, which is not the same as the value expected for this. The situation in SetInterval is similar.

<script type= "Text/javascript" >
  //this point to Window
  function shape (name) {
    this.name = name;
    This.timer = function () {alert (' My shape is ' +this.name)};
    SetTimeout (This.timer, M);
  New shape (' rectangle ');
</script>

were not passed in, respectively, with Chrome,firefox and IE9 experiments, are the results.

Workaround One:

<script type= "Text/javascript" >
    function shape (name) {
    this.name = name;
    This.timer = function () {alert (' My shape is ' +this.name)};
    var _this = this;
    settimeout (function () {_this.timer.call (_this)}, M);
  New shape (' rectangle ');
</script>

Set a local variable _this and place it in the SetTimeout function variable, and the timer executes call or apply to set the this value.

A function can call local variable _this, thanks to JavaScript closures. It involves the scope of the chain and other knowledge, interested can go to understand their own, here does not unfold.

Workaround Two:

This method is a little tall. SetTimeout and SetInterval are customized. It also extends the low version of IE browsers and does not support the issue of passing extra parameters to the delay function.

<script type= "Text/javascript" >//Custom settimeout and setinterval var __nativest__ = window.settimeout, __nativeSI__
 
  = Window.setinterval; Window.settimeout = function (Vcallback, ndelay/*, ARGUMENTTOPASS1, ARGUMENTTOPASS2, etc. *) {var othis = this, aarg
   s = Array.prototype.slice.call (arguments, 2);
   Return __nativest__ (vcallback instanceof function? function () {vcallback.apply (othis, Aargs);
  }: Vcallback, Ndelay);
   
  }; Window.setinterval = function (Vcallback, ndelay/*, ARGUMENTTOPASS1, ARGUMENTTOPASS2, etc. *) {var othis = this, aAr
   GS = Array.prototype.slice.call (arguments, 2);
   Return __nativesi__ (vcallback instanceof function? function () {vcallback.apply (othis, Aargs);
  }: Vcallback, Ndelay);
   
  };
    function shape (name) {this.name = name;
      This.timer = function (other) {alert (' I shape is ' +this.name);
    Alert (' Extra param are ' + other);
  };

  var rectangle = new shape (' rectangle '); Settimeout.call (REctangle, Rectangle.timer, M, ' other ');

 </script>

1. Set local variables and assign values to native settimeout and setinterval

2, extended settimeout and setinterval,aargs by dividing arguments this variable to obtain an additional parameter array

3, with Vcallback instanceof function to determine whether this is a function or code, if it is a function with apply to execute

4, settimeout with call execution, set this object, as well as other func, delay and other parameters

5, by the way to expand Settimeout,ie lower version of the browser can also perform additional parameters

A distinction between settimeout and setinterval

<script type= "Text/javascript" >
 settimeout (function () {/
  * Some long block of code ... * * settimeout
  ( Arguments.callee,
 
 m); SetInterval (function () {/
  * Some long block of code ... *
 );
</script>

It looks like two functions are the same, but it's not the same.

The interval between the execution of the settimeout callback function and the previous execution is at least 100ms (may be more, but not less than 100ms)

The setinterval callback function will attempt to execute every 100ms, regardless of whether the last execution completed, the interval is theoretically <=delay.

SetInterval:

<script type= "Text/javascript" >
    function Sleep (ms) {
      var start = new Date ();
      while (new Date ()-Start <= ms) {}
    }
    var endtime = null;
    var i = 0;
    
    SetInterval (count, MB);
    function count () {
      var elapsedtime = endtime? (New Date ()-endtime): M;
      i++;
      Console.log (' Current count: ' + i + ', ' + ' elapsed time: ' + elapsedtime + ' ms ');
      Sleep (m);
      Endtime = new Date ();
    }
</script>

From the Firefox firebug can be seen, the time interval is very irregular.

This is roughly the case: since the Count function executes much longer than the setinterval time interval, the timed-trigger thread generates an endless stream of asynchronous timed events and puts them at the end of the task queue, regardless of whether they have been processed, but once a timed event task has been processed, The remaining timed events in these permutations are executed sequentially.

SetTimeout:

<script type= "Text/javascript" >
    function Sleep (ms) {
      var start = new Date ();
      while (new Date ()-Start <= ms) {}
    }
    var endtime = null;
    var i = 0;
  SetTimeout (count, MB);
    function count () {
      var elapsedtime = endtime? (New Date ()-endtime): M;
      i++;
      Console.log (' Current count: ' + i + ', ' + ' elapsed time: ' + elapsedtime + ' ms ');
      Sleep (m);
      Endtime = new Date ();
      SetTimeout (count, MB);
</script>  

The above is the entire content of this article, I hope to learn JavaScript timer to help you.

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.