1、概念:JavaScript通过window方法,执行一个设定的时间间隔之后来执行的代码;
2、设定计时事件所要使用的方法:setInterval()、setTimeout();停止执行使用:clearInterval()、 clearTimeout();
3、setInterval()和setTimeout()的区别
setInterval():设置指定的间隔毫秒数,实现不停的执行指定的代码;
相对应的clearInterval()为停止事件的执行;
setTimeout():暂停指定的毫秒数后执行指定的代码,设定的代码只执行一次;
相对应的 clearTimeout()为停止事件的执行;
4、Dome演示
setTimeout()\clearTimeout()
<html> <meta charset = "utf-8"> <head> <title>计时事件演示</title> </head> <script type = "text/javascript"> function change(){ setTimeout(function(){getchange()},3000); } function getchange(){ var h = document.getElementById("hello"); h.innerHTML = '<div id = "new">你好,中国</div>'; } </script> <body> <h1 id = "word">三秒后变换文本</h1> <input type = "button" onclick = "change()" value = "确定"/><br/> <div id = "hello">今天,你好!</div> </body> </html>setInterval()\clearInterval()
<html> <head> <meta charset="utf-8"> <title>计时事件演示</title> </head> <script> var myVar=setInterval(function(){myTimer()},1000); function myTimer(){ var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("demo").innerHTML=t; } function stop(){ clearInterval(myVar); } </script> <body> <h1>在页面显示一个时钟</h1> <h2 id="demo"></h2> <input type = "button" value = "暂停" onclick = "stop()"/> </body> </html>