0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】setIntervalの使い方

Last updated at Posted at 2024-11-19

setIntervalとは

setIntervalは、指定した間隔で関数を繰り返し実行するための関数です。

基本構文

setInterval(function, milliseconds);
  • function: 繰り返し実行したい関数または関数の参照
  • milliseconds: 関数を実行する間隔(ミリ秒単位)

使い方

以下に、setIntervalを使用して1秒ごとにメッセージをコンソールに表示する例を示します。

function greet() {
    console.log("こんにちは!1秒ごとにこのメッセージが表示されます。");
}

// 1000ミリ秒(1秒)ごとにgreet関数を実行
const intervalId = setInterval(greet, 1000);

実行の停止

setIntervalは、指定した間隔で関数を永遠に実行し続けます。これを停止するには、clearInterval関数を使用します。clearIntervalには、setIntervalが返すIDを渡します。

// 5秒後にsetIntervalを停止
const intervalId = setTimeout(() => {
    // ...
    clearInterval(intervalId);
    console.log("メッセージの表示を停止しました。");
}, 5000);

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?