LoginSignup
9
9

More than 5 years have passed since last update.

javascriptで、非同期処理を永久に繰り返す

Posted at

簡単に言うと、while(true)の非同期版みたいな感じ。npm / bowerのasync.foreverというのがあるのですが、これだとstart / stop機能がないので、この機能を加えたものを再実装してみました。

概念的にはスレッドと違いますが、ユースケースはスレッドと近く、バックグラウンドスレッド的な使い方をすることができます。

function forever(handler, stopHandler){
    var isRunning = false;
    var shouldBeStopped = false;
    var _handler = function() {
        handler(function next(stop) {
            if(stop || shouldBeStopped){
                isRunning = false;
                stopHandler && stopHandler(stop);
            }else{
                _handler();
            }
        })
    }
    return {
        start: function(){
            shouldBeStopped = false;
            if(!isRunning){
                isRunning = true;
                _handler();
            }
        },
        stop: function(){
            shouldBeStopped = true;
        }
    }
}

  var infiniteTask = forever(function(next){
    asyncFunc(function(x){
       if(x){
         next(); // continue
       }else{
         next(true); // stop
       }
    })
  }, function(){
    console.log('task finished');
  });
  infiniteTask.start();
  infiniteTask.stop();
  // この場合、asyncFuncは一度だけ実行される
9
9
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
9
9