解釋JavaScript中的計時器工作原理


在JavaScript中,計時器是一個非常值得注意的功能。就像普通的計時器一樣,我們可以設定一個時間啟動計時器,並在特定時間後執行JavaScript中的函式或程式碼。

簡單來說,我們可以使用計時器在一段時間延遲後執行程式碼。例如,當你訪問某些網站時,它會在你訪問3到4分鐘後顯示註冊框,這可以透過JavaScript實現。我們可以設定延遲計時器來顯示註冊彈出框。

另一個現實生活中計時器的例子是應用程式內的廣告。當你開啟任何應用程式時,它會在2到3分鐘後開始顯示廣告,並在1到2分鐘的間隔內更改廣告。

因此,在JavaScript中設定計時器有兩種不同的函式,我們將在本教程中探討。

使用setTimeout()函式在特定時間後執行程式碼

setTimeout() 函式允許我們在特定延遲後執行程式碼。但是,它允許我們定義延遲。它只在特定延遲後執行一次程式碼。

setTimeout()函式執行時,它會啟動計時器,並在特定延遲後執行回撥函式。

語法

使用者可以按照以下語法使用setTimeout()函式。

let timeoutId = setTimeout(callback, delay);

在上述語法中,回撥函式也可以是箭頭函式來執行。

引數

  • 回撥函式 – 在延遲一段時間後要執行的函式。

  • 延遲 – 以毫秒為單位的延遲時間,在此時間後執行回撥函式。

返回值

setTimeout()函式返回一個唯一ID,我們可以用它來終止計時器。

示例

在下面的示例中,當用戶點選“啟動計時器”按鈕時,它將呼叫callTimer()函式。使用者可以看到它列印“callTimer函式首先執行”,2000毫秒後,它列印“此函式在一段時間延遲後執行”,因為setTimeout()函式在2000毫秒後呼叫回撥函式。

<html>
   <body>
      <h2> Using the setTimeOut() function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "callTimer()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         output.innerHTML += "Program execution started </br>";
         function callTimer() {
            output.innerHTML = "The callTimer function executed  <br/>";
            setTimeout(callback, 2000);
         }
         function callback() {
            output.innerHTML += "This function executed after some delay.";
         }
      </script>
   </body>
</html>

使用setInterval()函式以特定間隔執行函式

setTimeout()函式只執行一次回撥函式,但setInterval()函式會在我們作為setInterval()的第二個引數傳遞的每個間隔後執行程式碼。

語法

使用者可以按照以下語法使用setInterval()函式。

setInterval(callback, interval)

引數

  • 回撥函式 – setInterval()函式在每個間隔後呼叫的函式。

  • 間隔 – 以毫秒為單位的時間,在每個間隔後呼叫回撥函式。

返回值

setInterval()函式也像setTimeout()函式一樣返回唯一ID,我們可以用它來停止計時器。

示例

在這個例子中,我們使用了setInterval()函式來每1000毫秒呼叫一次回撥函式。使用者可以觀察到,當他們按下啟動計時器按鈕時,startInterval()函式將執行,這將呼叫setInterval()函式。setInterval()函式每秒呼叫一次回撥函式。

<html>
   <body>
      <h2> Using the <i> setInterval() </i> function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "startInterval()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         let count = 0;
         output.innerHTML += "Program execution started </br>";
         
         // when user clicks on the button, startInterval() function will be called
         function startInterval() {
            output.innerHTML = "The callTimer function executed <br/>";
            
            // the setInterval() function will call the callback function after every second.
            setInterval(callback, 1000);
         }
         function callback() {
            output.innerHTML += "This function executed for " + count + " time </br>";
            
            // update the count to track of howmany times a callback is called.
            count = count + 1;
         }
      </script>
   </body>
</html>

使用clearTimeout()和clearInterval()函式終止計時器

啟動計時器後,我們也需要停止它。我們可以使用clearTimeout()函式停止setTimeout()函式,使用clearInterval()函式停止setInterval()函式。

語法

// To stop the setTimeOut() function
clearTimeout(TimerId);

// To stop the setInterval() function
clearInterval(TimerId);

引數

  • 計時器ID – 由setTimeout()或setInterval()函式返回的唯一ID。

示例

在下面的示例中,我們使用setInterval()計時器函式每秒呼叫一次函式。此外,我們還跟蹤setInterval()函式呼叫回撥函式的次數。

在回撥函式中,我們使用if語句檢查計數是否大於3,如果大於3,則使用clearInterval()函式終止計時器。

<html>
   <body>
      <h2> Using the <i> clearInterval() </i> function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "startInterval()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         let count = 0;
         let TimerId = "";
         function startInterval() {
            TimerId = setInterval(() => {
               output.innerHTML += "count = " + count + "<br/>";
               count += 1;
               if (count > 3) {
                  clearInterval(TimerId);
               }
            }, 1000);
         }
      </script>
   </body>
</html>

在上面的輸出中,使用者可以觀察到它列印到計數=3,因為當計數大於3時,我們已經終止了計時器。

更新於:2023年1月5日

605 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告