setInterval的使用方法 javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h3 id="hid">0</h3> <script type="text/javascript"> var hid = document.getElementById("hid"); var num = 1; function myTime(){ hid.innerHTML = num; num++; } setInterval("myTime()",1000); // setInterval是每隔time毫秒執行一次函數 </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h3 id="hid">0</h3> <script type="text/javascript"> var hid = document.getElementById("hid"); var num = 1; var sid = null; // 存放setInterval function myTime(){ hid.innerHTML = num; if(num == 5){ clearInterval(sid); } num++; } sid = setInterval("myTime()",1000); // 存儲起來 </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h3 id="hid">0</h3> <button onclick="clearInterval(sid)">點擊中止</button> <script type="text/javascript"> var hid = document.getElementById("hid"); var num = 1; var sid = null; // 存放setInterval function myTime(){ hid.innerHTML = num; num++; } sid = setInterval("myTime()",1000); // 存儲起來 </script> </body> </html>