如何停止正在 JavaScript 中執行的函式?


若要停止正在執行的函式,請使用如下概念 −

document.getElementById().addEventListener().

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
</head>
<body>
<button type="button" id="call">Call the function</button>
<button type="button" id="halt">Stop the function execution </button>
<script>
   document.getElementById("call").addEventListener("click", callFunction);
   document.getElementById("halt").addEventListener("click", haltFunction);
   var timeValue = null;
   function callFunction() {
      timeValue = setInterval(function() {
         console.log("The call() is being executed....");
      }, 1000);
   }
   function haltFunction() {
      clearInterval(timeValue);
   }
</script>
</body>
</html>

若要執行上述程式,請儲存檔名 anyName.html(index.html) 並右鍵單擊檔案,然後在 VS 程式碼編輯器中選擇用即時伺服器開啟的選項。

輸出

單擊呼叫函式按鈕後,它將執行該函式。若要停止函式,請單擊停止函式執行 按鈕。

快照如下 −

更新於: 16-Jul-2020

4K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.