如何在一段時間後或 JavaScript 中的若干操作後使 setInterval() 停止?


在一段時間後利用一些條件來停止。

下面的程式碼將在半分鐘後停止。

以下是程式碼 −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<script>
   var now = new Date().getTime();
   var interval = setInterval(function () {
      if (new Date().getTime() - now > 30000) {
         clearInterval(interval);
         return;
      }
      console.log("working");
   }, 2000);
</script>
</html>

要執行以上程式,請將檔名儲存為 anyName.html(index.html) 並右鍵單擊該檔案。在 VS Code 編輯器中選擇“Use live server 開啟”選項。

輸出

這將產生以下輸出 −

更新於:2020 年 10 月 26 日

2K+ 訪問量

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.