LoginSignup
48
46

More than 5 years have passed since last update.

$.DeferredでsetTimeoutの取り扱いを簡単にする

Last updated at Posted at 2013-08-01

setTimeoutを使って複雑な非同期処理を書くのは、タイマーIDの管理が大変でやりたくない。
Deferredオブジェクトならそこら辺うまいこと取り扱えるんで、よくDeferredオブジェクトでsetTimeoutをラップして使う。

$.extend({
    wait: function(duration){
        var dfd = $.Deferred();
        setTimeout(dfd.resolve, duration);
        return dfd;
    }
});

こんな感じで使える

var time = +new Date();

// 1秒待つ
$.wait(1000).done(function(){
    console.log(new Date() - time); //=> 大体 1000
});

// 2秒たったらキャンセルする
var timer = $.wait(3000).fail(function(){
    console.log(new Date() - time); //=> 大体 2000
});
$.wait(2000).done(timer.reject);

// Deferredオブジェクトなので $.when が使える
$.when($.wait(1000), $.wait(2000), $.wait(3000)).done(function(){
    console.log(new Date() - time); //=> 大体 3000
});
48
46
4

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
48
46