Skip to content

Instantly share code, notes, and snippets.

@digiguru
Last active August 29, 2015 14:04
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 digiguru/2d16bb4abbf5b27a5350 to your computer and use it in GitHub Desktop.
Save digiguru/2d16bb4abbf5b27a5350 to your computer and use it in GitHub Desktop.
For faking ajax calls in jquery functions I use this...
var echoDataAfterTime = function(echoData, waitTime) {
var dfd = new $.Deferred();
waitTime = waitTime || 1000 * 3; //3 second default (it's long but it proves a point)
console.log("Waiting for " + waitTime/1000 + " seconds");
setTimeout(function () {
console.log("Waited for " + waitTime/1000 + " seconds to return data", echoData);
dfd.resolve(echoData);
}, waitTime);
return dfd.promise();
};
@digiguru
Copy link
Author

digiguru commented Aug 1, 2014

Usage suggestion:

You can very easily create a deferred.

echoDataAfterTime({title: "hello world"}).then(function() {
  console.log("this will happen second");
});
console.log("this will happen first");

output would be...

//"Waiting for 3 seconds"
//"this will happen first"
// 
// ( 3 second pause)
// 
//"Waited for 3 seconds to return data", {title: "hello world"}
//"this will happen second"

You can change the length of the wait

echoDataAfterTime({title: "hello world"}, 5000)

will output
//"Waiting for 5 seconds"
//
// ( 5 second pause)
//
//"Waited for 5 seconds to return data", {title: "hello world"}

But if you have a plugin that expects a deferred to get more data, it might look like this:

var globalCounter = 0;

$("#item").myPlugin({
   getMoreData: function() {
         globalCounter++;
         return echoDataAfterTime({
                  id: globalCounter
         });
   }
});

If the plugin calls "getMoreData" twice in succession the output would look like:

//"Waiting for 3 seconds"
//"Waiting for 3 seconds"
// 
// ( 3 second pause)
// 
//"Waited for 3 seconds to return data", {id: "1"}
//"Waited for 3 seconds to return data", {id: "2"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment