JavaScript 一个设定的时间间隔之后来执行代码,称之为计时事件。
主要通过两个方法来实现:
1.setInterval() - 间隔指定的毫秒数不停地执行指定的代码。
2.setTimeout() - 暂停指定的毫秒数后执行指定的代码
并且,这两个方法都是window对象的方法。
一、setInterval()方法
该方法值得是间隔一定的毫秒数不停的执行指定的代码。
语法:window.setInterval(”js代码,函数等“,毫秒数);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计时器-setInterval</title> </head> <body> <form> <input type="button" value="开始计数" onclick="start()" /> <input type="button" value="停止计数" onclick="stop()" /> </form> <div id="div2"></div> <script type="text/javascript"> var a=0; var timer = null; function start(){ timer = setInterval(function(){ a ++; document.getElementById("div2").innerHTML = "计数:"+a; },1000); } function stop(){ clearInterval(timer); } </script> </body> </html>
二、setTimeout()方法
指的是指定的毫秒数后执行指定的代码或方法。
语法:window.setTimeout("javascript 函数",毫秒数);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计时器-setTimeout</title> </head> <body> <form> <input type="button" value="三秒后执行" onclick="count()" /><br /><br /> </form> <div id="div1"></div> <hr /> <form> <input type="button" value="开始计数" onclick="start()" /> <input type="button" value="停止计数" onclick="stop()" /><br /><br /> </form> <div id="div2"></div> <script type="text/javascript"> function count(){ //setTimeout("alert('时间到了')",3000); setTimeout(function(){ hide(); },3000); } function hide(){ var div1 = document.getElementById('div1'); div1.innerHTML = "hello world"; div1.style.height = div1.offsetHeight+200+"px"; div1.style.background = "red"; } var a=0; var timer = null; function start(){ a += 1; document.getElementById("div2").innerHTML = "计数:"+a; timer = setTimeout("start();",1000); } function stop(){ clearTimeout(timer); } </script> </body> </html>
最后再强调:
setTimeout 在某个时间以后执行一个函数(只执行1次)
setInterval 让程序每个一定时间来调用函数1次