通过使用 JavaScript,我们有能力作到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:

setInterval() - 间隔指定的毫秒数不停地执行指定的代码,clearInterval() 方法用于停止 setInterval() 方法执行的函数代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript计时事件</title>
</head>

<body>
<p>在页面显示时钟</p>
<p id="demo"></p>
<button onClick="myStopFunction()">停止时钟</button>
<script>
   var myVar=setInterval(function(){myTimer()},1000);
   function myTimer(){
      var d=new Date();
      var t=d.toLocaleTimeString();
      document.getElementById("demo").innerHTML=t;
   }
   function myStopFunction(){
      window.clearInterval(myVar);
   }
</script>
</body>
</html>

setTimeout() - 暂停指定的毫秒数后执行指定的代码,clearTimeout() 方法用于停止执行setTimeout()方法的函数代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript计时事件</title>
</head>

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