LoginSignup
0
1

More than 3 years have passed since last update.

setTimeout()を使ったループ処理

Posted at
qiita.js
'use strict';

{
function showTime() {
console.log(newDate());
setTimeout(showTime, 1000);//繰り返す値と、1000ミリ秒(1秒)を引数に渡す
};

showTime();
}

結果として現在時刻を1秒毎に出力する。

上のコードだとループ処理になるため、指定した数字で止める処理は↓

qiita.js
'use strict';

{
 let i = 0;
 function showTime() {
    console.log(newDate());
    const timeoutId = setTimeout(showTime, 1000);
    i++;
    if(i > 3){  //3より大きい値になるまで処理
      clearTimeout(timeoutId)//clearTimeoutにsetTimeoutの返り値を定数に入れる
    }
  };

showTime();
}
0
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
0
1