window.setInterval(function, delay)
setInterval
は、functionに与えられた関数・処理をdelay(ms)ごとに繰り返す処理。window.setTimeout(function, delay)
setTimeout
は、functionに与えられた関数・処理をdelay(ms)後に実行する処理。
setInterval
で定義された処理を止める場合は、setInterval
の戻り値に対してclearInterval
を、
setTimeout
で定義された処理を止める場合は、setTimeout
の戻り値に対してclearTimeout
を行う。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> (function(){ // windowのロード時にidがdatetimeのエレメントに時刻を挿入 window.addEventListener("load",function(){ document.getElementById("datetime").innerText = new Date().toString(); },false); // 1000ms毎にidがdatetimeのエレメントの時刻を書き換え var interVal = window.setInterval(function(){ document.getElementById("datetime").innerText = new Date().toString(); }, 1000); // 10000ms後に繰り返し処理を終了する window.setTimeout(function(){ clearInterval(interVal); }, 10000); })(); </script> </head> <body> <p id="datetime"></p> </body> </html>