LoginSignup
7
5

More than 5 years have passed since last update.

js setTimeout ネスト避ける

Last updated at Posted at 2015-11-18
setTimeout(function() {
  // 処理
  setTimeout(function() {
    // 処理
    setTimeout(function() {
      // 見た目がキモいので避けたい
    }, 200);
  }, 100);
}, 300);

キモい。
毎回待ち時間が違うsetTimeoutを連続で呼びたいのですが...。

ライブラリなし、ES5で動くコードでもっと綺麗にしたいです。
てことでこんなコード書いてみました。

var TimerSetter = function(){
      this.waitMsec = 0;
    };
TimerSetter.prototype = {
  wait: function(func, msec) {
    this.waitMsec += msec;
    setTimeout(func, this.waitMsec);
    return this;
  }
};

// .....
var time = new TimerSetter();
time.wait(function () {
      // 処理
    }, 200)
    .wait(function () {
      // 処理
    }, 100)
    .wait(function () {
      // 処理
    }, 300)

コード量が増えるのと、実際に実行している内容が変わってるんだけど(全てのsetTimeoutをほぼ同時に実行している)特に問題は起きてません。

でもなんか良くない気もします。

このコードどうでしょうか。

7
5
5

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
7
5