Skip to content

Instantly share code, notes, and snippets.

@maxim75
Created May 19, 2011 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxim75/980268 to your computer and use it in GitHub Desktop.
Save maxim75/980268 to your computer and use it in GitHub Desktop.
Using deferred in jQuery
<html>
<head>
<style>
#map
{
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="div1">
</div>
<div id="map">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
function deferredTest(num, func)
{
var dfd = new $.Deferred();
console.log("deferredTest");
setTimeout(function() {
if(func(num))
{
console.log("resolve");
dfd.resolve( num );
}
else
{
console.log("reject");
dfd.reject( num );
}
}, 5000);
return dfd.promise();
}
$.when(deferredTest(9, function(x) { return (x > 10); }),
deferredTest(14, function(x) { return (x < 15); }))
.done(function(x) { console.log("done = " + x); })
.fail(function(x) { console.log("fail = " + x); });
console.log("asas");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment