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

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执行一次,不论上次是否执行完毕,时间间隔理论上是会

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
了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python vs. JavaScript:社區,圖書館和資源Python vs. JavaScript:社區,圖書館和資源Apr 15, 2025 am 12:16 AM

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C到JavaScript:所有工作方式從C/C到JavaScript:所有工作方式Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具