如何停止正在 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 程式碼編輯器中選擇用即時伺服器開啟的選項。
輸出

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

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP