setTimeoutを使って関数を呼び出す
setInterval(関数名,ミリ秒)とすることで、特定のメソッドを指定したミリ秒間隔で呼び続けることができますが、setTimeoutはsetTimeout(関数名,ミリ秒)とすることで、特定のメソッドをミリ秒後に1度だけ呼ぶことができます。
例えば以下の例では、ボタンがクリックされてから、2秒後にDateオブジェクトが生成されてコンソールに表示されています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Javascript Practice</title>
</head>
<body>
<button type="click" id="button">showDatePerSecondを呼ぶ</button>
<script src="main.js"></script>
</body>
</html>
function showDateTimePerSecond() {
console.log(new Date());
};
document.getElementById('button').onclick = function(){
setTimeout(showDateTimePerSecond,2000);
}
setTimeout(関数名,ミリ秒)で繰り返し関数を呼ぶ
setTimeoutもsetIntervalと似たような使い方ができます。
以下の例では、showDateTimePerSecondの関数内でsetTimeoutを呼び、引数にshowDateTimePerSecondを取ることで繰り返しの処理をしています。
function showDateTimePerSecond() {
console.log(new Date());
setTimeout(showDateTimePerSecond, 1000);
};
showDateTimePerSecond();
clearTimeout()で処理を止める
setTimeoutの繰り返しを止めるには、clearTimeoutというメソッドが用意されています。
以下の例では変数iが3になった時点でclearTimeoutを呼んで処理を止めています。
let i = 0;
function showDateTimePerSecond() {
console.log(new Date());
const timeoutId = setTimeout(showDateTimePerSecond, 1000);
i ++;
if (i > 2) {
clearTimeout(timeoutId);
}
};
showDateTimePerSecond();
setIntervalとsetTimeoutの違い
setIntervalで繰り返し処理を行うのと、setTimeoutで繰り返し処理を行うのではどのような違いがあるでしょう?
以下のサイトがとてもわかりやすいです。要は、
setInterval ← 呼び出しを行なった関数の処理終了は関係なく、指定された時間になったら問答無用で引数で渡されている関数を呼ぶ。
setTimeoutで繰り返し処理 ← 呼び出しを行なった関数の処理が終わった後、指令された時間を置いて、引数で渡されている関数を呼ぶ。