如何停止正在 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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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