1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[JavaScript]setIntervalとsetTimeout

Posted at

setIntervalとsetTimeoutについて

今回はこの二つの基本的な使い方について解説したいと思います。
これらのメソッドは自動更新などに使うことができ、引数に時間を指定して関数を一定間隔で呼び出すことができます。

setInterval();

まずsetIntervalについて説明します。
setIntervalメソッドは第一引数に指定した関数を第二引数に指定した時間の間隔でなんども呼び出します。
サンプルコードを下記に記します。

setInterval.js
$(function(){
  setInterval('sample', 1000);
});
function sample() {
 //処理を記入
  };

これで定義できました。上記に処理は1000ミリ秒つまり、1秒ごとにsampleを実行するという意味になります。
条件分岐などを使って処理を止めたりしないと常に1秒ごとに呼び出されてしまいますので、気をつけましょう。

setTimeout();

setTimeoutはsetIntervalと違い、指定した時間後に関数を一度しか呼び出しません。

setTimeout.js
$(function(){
  sample();
});
function sample() {
 //処理を記入
  };
setTimeout(sample, 5000);

上記の意味は関数sampleを5秒後に呼び出すという意味になります。
関数sampleを繰り返さないのがポイントです。

ただし以下のように記述することによりsetIntervalのように繰り返すこともできます。

setTimeout.js
$(function(){
  sample();
});
function sample() {
 //処理を記入
 setTimeout(sample, 5000);
  };

このようにsetTimeoutを関数内に定義することによりsetInterval同様5秒ごとに関数sampleを呼び出すという意味になります。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?