0
0

More than 3 years have passed since last update.

JavaScript勉強の記録その22:setTimeoutとclearTimeoutを使って関数を呼び出す

Last updated at Posted at 2020-01-19

setTimeoutを使って関数を呼び出す

setInterval(関数名,ミリ秒)とすることで、特定のメソッドを指定したミリ秒間隔で呼び続けることができますが、setTimeoutはsetTimeout(関数名,ミリ秒)とすることで、特定のメソッドをミリ秒後に1度だけ呼ぶことができます。

例えば以下の例では、ボタンがクリックされてから、2秒後にDateオブジェクトが生成されてコンソールに表示されています。

index.html
<!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>
index.js
function showDateTimePerSecond() {
   console.log(new Date());
};

document.getElementById('button').onclick = function(){
  setTimeout(showDateTimePerSecond,2000);
}

image.png

setTimeout(関数名,ミリ秒)で繰り返し関数を呼ぶ

setTimeoutもsetIntervalと似たような使い方ができます。
以下の例では、showDateTimePerSecondの関数内でsetTimeoutを呼び、引数にshowDateTimePerSecondを取ることで繰り返しの処理をしています。

index.js
function showDateTimePerSecond() {
  console.log(new Date());
  setTimeout(showDateTimePerSecond, 1000);
};

showDateTimePerSecond();

clearTimeout()で処理を止める

setTimeoutの繰り返しを止めるには、clearTimeoutというメソッドが用意されています。
以下の例では変数iが3になった時点でclearTimeoutを呼んで処理を止めています。

index.js
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で繰り返し処理 ← 呼び出しを行なった関数の処理が終わった後、指令された時間を置いて、引数で渡されている関数を呼ぶ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0