间歇调用:每隔指定的时间就执行一次代码
超时调用:在指定的时间过后执行代码
HTML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html>
<html> <head> <title>Javascript setTimeout</title> <script type="text/javascript"> //不建议传递字符串 //setTimeout("alert('Hello World')", 1000); //推荐的调用方式 var timeoutId = setTimeout(function(){ alert("Hello World!"); }, 2000); //注意:把它取消 clearTimeout(timeoutId); </script> </head> <body> </body> </html> |
HTML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html>
<html> <head> <title>Javascript setInterval</title> <script type="text/javascript"> //不建议传递字符串 //setInterval("alert('Hello World')", 1000); //推荐的调用方式 var num = 0; var max = 10; var IntervalId = null; function increaseNumber(){ ++num; document.body.innerHTML = ""; document.write(num); if (num > max) { clearInterval(IntervalId); alert('Done!'); } } IntervalId = setInterval(increaseNumber, 1000); </script> </head> <body> </body> </html> |