如何在 JavaScript 中停止执行函数?
javascriptweb developmentobject oriented programming更新于 2025/8/19 5:32:17
要在执行函数时停止它,请使用 −
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 代码编辑器中使用实时服务器打开选项。
输出

单击"调用函数"按钮时,它将执行该函数。要停止该函数,请单击停止函数执行按钮。
快照如下 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

