"Too bad you can't use window.setTimout and have it implement the jQuery Deferred interface."
We're all upset about that. So...
"Wait. What? Now you can?!?"
Right. Now you can. I searched the internet and couldn't find an existing one, to my surprise. I wrote it for you though.
It's almost as simple as my sample code in this post explaining the basics of Deferred with the addition of an actual setTimeout... Make a $.Deferred. Call the provided func in a setTimeout, using the provided delay and parameters. After the call to the provided func, call .resolve, and in a catch block, call .reject.
"How do you use it?"
Use it just like setTimeout setTimeout:
setTimeout(function(){ console.log("I'm in the future. " + new Date()); }, 2000);
My new $.defer method:
$.defer(function(){ console.log("I'm in the future. " + new Date()); }, 2000);
It's the same. You can even pass parameters, just like setTimout. (I didn't bother implementing the overload that takes a string and eval's it, because who cares)
"So what's the big deal?"
- It works the same way as your beloved setTimeout, only with the $.defer, you can chain callbacks on the end...
$.defer(function(){ console.log("I'm in the future. " + new Date()); }, 2000) .done(function(){ console.log("All done"); });
and you get all the benefits of the rest of the callbacks - done/fail/then/always, etc. - You can use it anywhere that expects a promise - for example, you can use it as a participant in jQuery's $.when()!
- Since there are callbacks, you have a way to get the return value of the function that you called.
$.defer(function(){ return "no you didn't"; }, 2000) .done(function(x){ console.log(x); // x is "no you didn't" });
- It's cancel-able. (with optional bool parameter to reject/not reject)
$.defer(function(){ console.log("Doing work..."); }, 2000) .progress(function(d){ console.log("Sorry to have to cancel this."); d.cancel(); }) .done(function(){ console.log("Won't get here."); }) .fail(function(){ console.log("This will happen"); });
-
You can use it without the function parameter to return a promise that will resolve in [delay] milliseconds
return $.defer(100);
The delay is optional too. The default delay of 0 (zero) will be used.
return $.defer(function(){alert("ASYNC!");});
or
return $.defer();