通过使用 JavaScript,我们有能力作到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。 在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:
setInterval() - 间隔指定的毫秒数不停地执行指定的代码。 clearInterval()方法用于停止 setInterval() 方法执行的函数代码。setTimeout() - 暂停指定的毫秒数后执行指定的代码 clearTimeout() 方法用于停止执行setTimeout()方法的函数代码。Note: setInterval() 和 setTimeout() 是 HTML DOM Window对象的两个方法。
setInterval()方法以及clearInterval()方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试setInterval方法</title> </head> <body> <p>页面上显示时钟:</p> <p id="demo"></p> <script> var myVar=setInterval(function(){myTimer()},1000); function myTimer(){ var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("demo").innerHTML=t; } function myStopFunction(){ clearInterval(myVar); } </script> <hr> <button onclick="myStopFunction()">停止时钟</button> </body> </html>效果:
setTimeout()以及clearTimeout()方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试clearTimeout方法</title> </head> <body> <p>点击第一个按钮等待2秒后出现"Hello"弹框。</p> <p>点击第二个按钮来阻止第一个函数运行。(你必须在2秒之前点击它)。</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>效果: