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?

More than 5 years have passed since last update.

JavaScript勉強の記録その21:setIntervalとclerIntervalを使って関数の呼び出し

Last updated at Posted at 2020-01-19

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

setInterval(関数名,ミリ秒)とすることで、特定のメソッドを指定したミリ秒間隔で呼び続けることができます。 
以下の例では、showDateTimePerSecondという関数を1秒間隔で呼び、Dateオブジェクトを生成し、コンソールに表示しています。

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

setInterval(showDateTimePerSecond,1000)

//=>Sun Jan 19 2020 21:27:11 GMT+0900 (日本標準時)
//=>Sun Jan 19 2020 21:27:12 GMT+0900 (日本標準時)
//=>.....

clearIntervalを使ってsetIntervalを止める

反対にclearIntervalを利用すれば、setIntervalで呼び続ける処理を止めることができます。
以下の例では変数iが3になった時点で、clearIntervalを呼んで、処理を止めています。

index.js
let i = 0;

function showDateTimePerSecond() {
  console.log(new Date());
  i++
  if (i > 2) {
    clearInterval(intervalId);
  }
};


const intervalId = setInterval(showDateTimePerSecond,1000);
console.log(intervalId);

//=>1
//=>Sun Jan 19 2020 21:36:05 GMT+0900 (日本標準時)
//=>Sun Jan 19 2020 21:36:06 GMT+0900 (日本標準時)
//=>Sun Jan 19 2020 21:36:07 GMT+0900 (日本標準時)

clearIntervalは引数にsetIntervalの返り値を渡してあげることによって、どのsetIntervalを止めるか指定することができます。
上記の例ではあえて、console.log(intervalId)として、setInterval()の返り値を表示させています。
つまり上記の例では返り値が1のsetIntervalを止めているということです。

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?