<!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>
<body>
<p>点击第一个按钮等待3秒后出现"Hello"弹框。</p>
<p>点击第二个按钮来阻止第一个函数运行。(你必须在3秒之前点击它)。</p>
<button onclick="myFunction()">点我</button>
<button onclick="myStopFunction()">停止弹框</button>
<script>
var myVar;
function myFunction() {
myVar = setTimeout(function () {
alert("Hello");
}, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
</script>
</body>
</html>
运行结果