Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Last active April 4, 2016 20:51
Show Gist options
  • Save kidGodzilla/3d449f208f1401d0976b5a9510d86e31 to your computer and use it in GitHub Desktop.
Save kidGodzilla/3d449f208f1401d0976b5a9510d86e31 to your computer and use it in GitHub Desktop.
Deferred Javascript Execution Class: Defer the execution of a bit of Javascript until a condition is met
var deferredExecutionTimers = window.deferredExecutionTimers = {};
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function deferExecution (condition, callback, interval) {
if (!deferredExecutionTimers) window.deferredExecutionTimers = {};
// Generate a new UUID to track this timer
var uuid = s4() + s4() + s4();
interval = interval || 1000;
deferredExecutionTimers[uuid] = setInterval(function () {
if (condition && typeof(condition) === "function") condition = condition();
if (condition) {
if (callback && typeof(callback) === "function") callback();
clearTimeout(deferredExecutionTimers[uuid]);
}
}, interval);
}
// Example
deferExecution (function () {
return window.foo && window.foo === "bar";
}, function () {
console.log('done!');
});
setTimeout(function () {
window.foo = "bar";
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment