首頁 >web前端 >js教程 >理解javascript計時器中的setTimeout與setInterval_javascript技巧

理解javascript計時器中的setTimeout與setInterval_javascript技巧

WBOY
WBOY原創
2016-05-16 15:14:081262瀏覽

1. Explanation

1. Overview

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

setInterval: Periodically call a function or execute 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. This ID can then be used as a parameter of the window.clearTimeout method
  • func is the function you want to execute after delay milliseconds
  • code In the second syntax, it refers to the code you want to execute after delay milliseconds
  • delay is the number of milliseconds of delay (one second is equal to 1000 milliseconds). The function call will occur after this delay. But the actual delay time may be slightly longer
  • Standard browsers and IE10 support the function of passing extra parameters to the delayed 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 of this repeated operation and can be passed as a parameter to clearInterval().
  • func is the function you want to call repeatedly.
  • code is another syntax application, which refers to a code consisting of a string that you want to execute repeatedly
  • delay is the number of milliseconds of each delay (one second equals 1000 milliseconds), after which each call to the function will occur. Like setTimeout, the actual delay may be slightly longer.
  • Standard browsers and IE10 support the function of passing extra parameters to the delayed function in the first syntax
<script type="text/javascript">
  setTimeout( function(param){ alert(param)} , 100, 'ok'); 
</script> 

I briefly tested the fifth item, using firefox and IE9 on my computer. The former can pop up ok smoothly, while the latter pops up undefined.

2. “this” question

The code called by setTimeout() runs in an execution environment completely separate from the function in which it is located. This will cause the this keyword contained in these codes to point to the window (global object) object, which is different from the expected this The values ​​are not the same. The situation with setInterval is similar.

<script type="text/javascript">
  //this指向window
  function shape(name) {
    this.name = name;
    this.timer = function(){alert('my shape is '+this.name)};
    setTimeout(this.timer, 50);
  }
  new shape('rectangle');
</script>

It was not passed in. I tried it with chrome, firefox and IE9, and the result was the same.

Solution 1:

<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)}, 50);
  }
  new shape('rectangle');
</script>

Set a local variable _this, and then put it in the function variable of setTimeout. The timer executes call or apply to set the this value.

function can call the local variable _this, thanks to Javascript closures. It involves scope chain and other knowledge. If you are interested, you can learn about it yourself. I will not go into it here.

Solution 2:

This method is a bit fancy. Customized setTimeout and setInterval. It also extends the problem that lower versions of IE browsers do not support passing additional parameters to the delay function.

<script type="text/javascript"> 
  //自定义setTimeout与setInterval
  var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
 
  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
   var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
   return __nativeST__(vCallback instanceof Function &#63; function () {
    vCallback.apply(oThis, aArgs);
   } : vCallback, nDelay);
  };
   
  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
   var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
   return __nativeSI__(vCallback instanceof Function &#63; function () {
    vCallback.apply(oThis, aArgs);
   } : vCallback, nDelay);
  };
   
  function shape(name) {
    this.name = name;
    this.timer = function(other){
      alert('my shape is '+this.name);
      alert('extra param is '+ other);
    };
  }
  var rectangle = new shape('rectangle');

  setTimeout.call(rectangle, rectangle.timer, 50, 'other');
</script>

1. Set local variables and assign values ​​to native setTimeout and setInterval

2. Extend setTimeout and setInterval, aArgs obtains additional parameter arrays by splitting the arguments variable

3. Use vCallback instanceof Function to determine whether this is a function or code. If it is a function, use apply to execute it

4. SetTimeout is executed with call, and sets this object, as well as other func, delay and other parameters

5. By extending setTimeout, browsers with lower versions of IE can also execute additional parameters

3. The difference between setTimeout and setInterval

<script type="text/javascript">
 setTimeout(function(){
  /* Some long block of code... */
  setTimeout(arguments.callee, 100);
 }, 10);
 
 setInterval(function(){
  /* Some long block of code... */
 }, 100);
</script>

看上去,两个功能是差不多的,但是里面其实是不一样的。

setTimeout回调函数的执行和上一次执行之间的间隔至少有100ms(可能会更多,但不会少于100ms)

setInterval的回调函数将尝试每隔100ms执行一次,不论上次是否执行完毕,时间间隔理论上是会<=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, 100);
    function count() {
      var elapsedTime = endTime &#63; (new Date() - endTime) : 100;
      i++;
      console.log('current count: ' + i + '.' + 'elapsed time: ' + elapsedTime + 'ms');
      sleep(200);
      endTime = new Date();
    }
</script>

从firefox的firebug可以查看到,时间间隔很不规则。

情况大致是这样的:由于count函数的执行时间远大于setInterval的定时间隔,那么定时触发线程就会源源不断的产生异步定时事件,并放到任务队列尾而不管它们是否已被处理,但一旦一个定时事件任务处理完,这些排列中的剩余定时事件就依次不间断的被执行。

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, 100);
    function count() {
      var elapsedTime = endTime &#63; (new Date() - endTime) : 100;
      i++;
      console.log('current count: ' + i + '.' + 'elapsed time: ' + elapsedTime + 'ms');
      sleep(200);
      endTime = new Date();
      setTimeout(count, 100);
    }
</script>  

以上就是本文的全部内容,希望对大家学习javascript定时器有所帮助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn