LoginSignup
1
1

More than 5 years have passed since last update.

何かがtrueになるまで定期的に実行する非同期ループ

Posted at

たとえばポーリングなど何かしらの条件が満たされるまで定期的にチェックし続けたいような処理をきれいにかけないか試してみた例。

limit はチェック回数だけど、タイムアウトでもいいかもしれない。

  function execution(func, interval, limit) {
    var id, count;
    setInterval(function () {
      count++;
      if(func.call() || (!isNaN(limit) && limit === count)) {
        clearInterval(id);
      }
    }, interval);
  }
execution(function() {
  if(Math.random() > 0.5) return false; //条件に満たない
  // Do something.
  return true;
}, 100);
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