Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created March 14, 2011 16:39
Show Gist options
  • Select an option

  • Save ericmoritz/869419 to your computer and use it in GitHub Desktop.

Select an option

Save ericmoritz/869419 to your computer and use it in GitHub Desktop.
Defers execution of a callback until a condition is true
var defer_until = function(conditional,
callback,
timeout) {
timeout = timeout || 10; // Default the timeout to 10ms
// Build a closure for this defer job
var timeout_callback = function() {
// If the conditional is true, fire off the callback
if(conditional()) {
callback();
// otherwise, create a new timeout
} else {
setTimeout(timeout_callback, timeout);
}
}
// Fire off the fire check of the conditional
timeout_callback();
}
var x, y;
jQuery.getJSON(url1, function(data) { x = data; render_view(x, y); });
jQuery.getJSON(url2, function(data) { y = data; render_view(x, y); });
function render_view(x, y) {
if(x && y) {
// Do rendering
}
}
var x, y;
jQuery.getJSON(url1, function(data) { x = data; });
jQuery.getJSON(url2, function(data) { y = data; });
defer_until(function() { return x && y; }, function() { render_view(x, y); }, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment