JavaScript - 定時事件



什麼是定時事件?

JavaScript 定時事件用於僅執行一次或多次指定時間後執行程式碼。在 JavaScript 中,您可以使用定時事件來控制何時執行特定任務。

'window' 物件包含用於定時事件的各種方法,您可以使用這些方法來安排任務。您可以使用 window 物件呼叫這些方法,也可以不使用它。

以下是可用於安排任務的方法列表。

方法 描述
setTimeout() 僅執行一次 N 毫秒後的程式碼。
clearTimeout() 清除使用 setTimeOut() 方法設定的超時。
setInterval() 每隔 N 毫秒執行一次特定任務。
clearInterval() 清除使用 setInterval() 方法設定的間隔。

讓我們透過下面的示例瞭解定時事件。

setTimeout() 方法

<html>
<body>
   <div id = "output">The message will be printed after 2000 milliseconds! <br></div>
   <script>
      setTimeout(() => {
         document.getElementById('output').innerHTML += 'Hello World <br>';
      }, 2000);
   </script>
</body>
</html>

輸出

The message will be printed after 2000 milliseconds!
Hello World

clearTimeout() 方法

在下面的示例中,我們使用 setTimeout() 方法在 3000 毫秒後列印 'hello world'。我們使用 clearTimeout() 方法來阻止 setTimeout() 方法執行。

示例

<html>
<body>
   <p>Message will print after 3 seconds.</p>
   <p>Click the button to prevent timeout to execute.</p>
   <p id="demo"></p>
   <button onclick="stop()">Clear Timeout</button>
   <script>
      const myTimeout = setTimeout(greet, 3000);
      function greet() {
         document.getElementById("demo").innerHTML = "Hello World!"
      }
      function stop() {
         clearTimeout(myTimeout);
      }
   </script>
</body>
</html>

輸出

The clearTimeout() Method

setInterval() 和 clearInterval() 方法

在下面的程式碼中,我們使用 setInterval() 方法在每秒後顯示遞增 10 的數字。

當數字變為 50 時,我們使用 clearInterval() 方法停止計時器。

示例

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let number = 10;
      let id = setInterval(() => {
         if (number == 50) {
            clearInterval(id);
            output.innerHTML += "The time is stopped."
         }
         output.innerHTML += "The number is: " + number + "<br>";
         number += 10;
      }, 1000);
   </script>
</body>
</html>

輸出

The number is: 10
The number is: 20
The number is: 30
The number is: 40
The time is stopped.The number is: 50

定時事件的即時用例

在這裡,您將學習定時事件的即時用例。

  • 用於動畫和過渡
  • 用於幻燈片和輪播
  • 用於倒計時
  • 用於使用者身份驗證超時
  • 自動儲存草稿,例如 Google 文件
  • 安排通知、電子郵件、訊息等。
  • 終止會話,例如銀行網站
  • 用於進度條

但是,還有其他用例。您可以使用 setTimeOut() 或 setInterval() 方法來實現上述功能。

接下來是什麼?

在接下來的章節中,您將詳細瞭解 setTimeOut()setInterval() 方法。

廣告