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

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

May 16, 2016 pm 03:14 PM
javascript setinterval settimeout 定時器

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何使用WebSocket和JavaScript實現線上語音辨識系統 如何使用WebSocket和JavaScript實現線上語音辨識系統 Dec 17, 2023 pm 02:54 PM

如何使用WebSocket和JavaScript實現線上語音辨識系統引言:隨著科技的不斷發展,語音辨識技術已成為了人工智慧領域的重要組成部分。而基於WebSocket和JavaScript實現的線上語音辨識系統,具備了低延遲、即時性和跨平台的特點,成為了廣泛應用的解決方案。本文將介紹如何使用WebSocket和JavaScript來實現線上語音辨識系

WebSocket與JavaScript:實現即時監控系統的關鍵技術 WebSocket與JavaScript:實現即時監控系統的關鍵技術 Dec 17, 2023 pm 05:30 PM

WebSocket與JavaScript:實現即時監控系統的關鍵技術引言:隨著互聯網技術的快速發展,即時監控系統在各個領域中得到了廣泛的應用。而實現即時監控的關鍵技術之一就是WebSocket與JavaScript的結合使用。本文將介紹WebSocket與JavaScript在即時監控系統中的應用,並給出程式碼範例,詳細解釋其實作原理。一、WebSocket技

如何利用JavaScript和WebSocket實現即時線上點餐系統 如何利用JavaScript和WebSocket實現即時線上點餐系統 Dec 17, 2023 pm 12:09 PM

如何利用JavaScript和WebSocket實現即時線上點餐系統介紹:隨著網路的普及和技術的進步,越來越多的餐廳開始提供線上點餐服務。為了實現即時線上點餐系統,我們可以利用JavaScript和WebSocket技術。 WebSocket是一種基於TCP協定的全雙工通訊協議,可實現客戶端與伺服器的即時雙向通訊。在即時線上點餐系統中,當使用者選擇菜餚並下訂單

如何使用WebSocket和JavaScript實現線上預約系統 如何使用WebSocket和JavaScript實現線上預約系統 Dec 17, 2023 am 09:39 AM

如何使用WebSocket和JavaScript實現線上預約系統在當今數位化的時代,越來越多的業務和服務都需要提供線上預約功能。而實現一個高效、即時的線上預約系統是至關重要的。本文將介紹如何使用WebSocket和JavaScript來實作一個線上預約系統,並提供具體的程式碼範例。一、什麼是WebSocketWebSocket是一種在單一TCP連線上進行全雙工

JavaScript與WebSocket:打造高效率的即時天氣預報系統 JavaScript與WebSocket:打造高效率的即時天氣預報系統 Dec 17, 2023 pm 05:13 PM

JavaScript和WebSocket:打造高效的即時天氣預報系統引言:如今,天氣預報的準確性對於日常生活以及決策制定具有重要意義。隨著技術的發展,我們可以透過即時獲取天氣數據來提供更準確可靠的天氣預報。在本文中,我們將學習如何使用JavaScript和WebSocket技術,來建立一個高效的即時天氣預報系統。本文將透過具體的程式碼範例來展示實現的過程。 We

簡易JavaScript教學:取得HTTP狀態碼的方法 簡易JavaScript教學:取得HTTP狀態碼的方法 Jan 05, 2024 pm 06:08 PM

JavaScript教學:如何取得HTTP狀態碼,需要具體程式碼範例前言:在Web開發中,經常會涉及到與伺服器進行資料互動的場景。在與伺服器進行通訊時,我們經常需要取得傳回的HTTP狀態碼來判斷操作是否成功,並根據不同的狀態碼來進行對應的處理。本篇文章將教你如何使用JavaScript來取得HTTP狀態碼,並提供一些實用的程式碼範例。使用XMLHttpRequest

javascript如何使用insertBefore javascript如何使用insertBefore Nov 24, 2023 am 11:56 AM

用法:在JavaScript中,insertBefore()方法用於在DOM樹中插入一個新的節點。這個方法需要兩個參數:要插入的新節點和參考節點(即新節點將要插入的位置的節點)。

java定時器表達式是什麼 java定時器表達式是什麼 Dec 27, 2023 pm 05:06 PM

定時器的表達式用於定義任務的執行計劃。定時器的表達式是基於「在給定的時間間隔之後執行任務」的模型。表達式通常由兩個部分組成:一個初始延遲和一個時間間隔。

See all articles