エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

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?

setIntervalのリスクと再帰的なsetTimeoutへの書き換え方

Posted at

とある社内プロジェクト、再起的に処理を実行したかったので安易にsetIntervalメソッドを使って実装しました。

社内レビューに出したところ「setIntervalは指定した時間内に処理を完了できなかったら、処理が途中で終わるリスクがある」とのご指摘をいただきました。

この記事では、setIntervalのリスクとそのリスクを回避するための代替案を記事にしました。

setIntervalのリスク

例えば以下のようなコードがあるとします。

function myFunction() {
  // 100msより長い時間実行される処理
}

setInterval(myFunction, 100);

この時、100msを超えた時点で前のmyFunctionの処理と次のmyFunctionの処理が重なってしまい、前のmyFunctionの処理が正常に完了しないリスクがあるとのことでした。

再帰的なsetTimeoutへの書き換え

setIntervalの代わりに、再帰的なsetTimeoutへ書き換えができます。
これにより、前回の関数実行が完了する前に次の関数実行が発生する可能性が低くなります。

以下は、再帰的なsetTimeoutを使用してsetIntervalを置き換える例です。

function myFunction() {
  // 100msより長い時間実行される処理
  
  setTimeout(myFunction, 100);
}

// 最初の関数実行をトリガーするために、最初のsetTimeoutを呼び出します。
setTimeout(myFunction, 100);

このように実装することで、myFunctionの処理が完了する前に次のsetTimeoutが発生することはありません。

参考

0
0
1

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

Comments

diywmk9
@diywmk9
function myFunction() {
 // 100msより長い時間実行される処理
 
 setTimeout(myFunction, 100);
}

// 最初の関数実行をトリガーするために、最初のsetTimeoutを呼び出します。
setTimeout(myFunction, 100);

初回も100ms後に実行したいのでなければ、いちいちsetTimeout()で呼び出す必要はありません。

function myFunction() {
  // 100msより長い時間実行される処理
  
  setTimeout(myFunction, 100);
}

// 最初の関数実行をトリガーするために、最初のsetTimeoutを呼び出します。
myFunction();

あるいは

(function myFunction() {
  // 100msより長い時間実行される処理
  
  setTimeout(myFunction, 100);
})();
0

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz), Shusaku Uesugi / Nicolas Ishihara(Vercel Inc.)

View event details

Being held Article posting campaign

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address