Skip to content

Instantly share code, notes, and snippets.

@isonno
Created March 1, 2015 17:38
Show Gist options
  • Save isonno/5e1fdd5a57c8542639ed to your computer and use it in GitHub Desktop.
Save isonno/5e1fdd5a57c8542639ed to your computer and use it in GitHub Desktop.
Demonstrate jQuery Deferred objects
/*
Documentation for <a href="http://learn.jquery.com/code-organization/deferreds/">jQuery Deferred</a> objects.
<p>
<div>
<button id="concur">Concurrent</button>
<button id="sequent">Sequential</button>
</div>
<p>
<div id="result">
</div>
*/
// Sample code illustrating how to use jQuery Deferred/Promise objects
function log(msg)
{
var s = $("#result").html();
s += msg + "<br>\n";
$("#result").html(s);
}
function clear() { $("#result").html(""); }
function delayThenDo( snooze )
{
var deferd = $.Deferred();
log("Starting " + snooze );
setTimeout( function() { log("Timeout: " + snooze);
deferd.resolve(snooze+1);}, snooze);
return deferd;
}
function finished(amount) { log("Promise result:" + amount); }
// Run all tasks concurrently, get result when last finishes
function testConcur() {
clear();
log("----Concurrent----");
$.when( delayThenDo(1000),
delayThenDo(1050),
delayThenDo(1080) ).done( finished );
log("...Exiting concurrent...");
}
// Run all tasks sequentially, output from previous feeds to next
function testSeq() {
clear();
log("----Sequential----");
var completion = function (p) {finished(p); return delayThenDo( p )};
var req = completion( 1000 );
req.then( completion ).then( completion ).done( finished );
log("...Exiting sequential...");
}
$("#concur").click( testConcur );
$("#sequent").click( testSeq );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment