定时器1:setTimeout()
<!DOCTYPE html> <html> <head> <title>js12.html</title> <script type="text/javascript"> function count() { setTimeout("alert('执行成功')",2000); //两秒钟后执行 alert } </script> </head> <body> <input type = "button" value = "计时开始" name = "timing" onclick="count()"> </body> </html>
第二种:setInterval()
<!DOCTYPE html> <html> <head> <title>js13.html</title> <script type="text/javascript"> var sec = 0; var timeId = setInterval("count();", 1000);//每隔 1 秒执行一次 count() function count() { document.getElementById("num").innerHTML = sec++; } function stop() { clearInterval(timeId); } </script> </head> <body> <font color="red" id ="num">0</font>秒钟 <input type = "button" value = "停止" onclick="stop();" > </body> </html>
结果: 点击 Stop,计时停止