Skip to content

Instantly share code, notes, and snippets.

@mikermcneil
Created October 9, 2012 21:18
Show Gist options
  • Save mikermcneil/3861518 to your computer and use it in GitHub Desktop.
Save mikermcneil/3861518 to your computer and use it in GitHub Desktop.
waitUntil
/**
* @test - condition to check
* @action - do something
* @tryInterval - how often to try (default to 50ms)
* @sharedTimer - if sharedTimer is specified, clear it when action is fired
* @eachTime - function to run each time the condition is checked
* returns timer
*/
function waitUntil (test,action,tryInterval,sharedTimer,eachTime) {
var timer = setInterval(function() {
typeof eachTime === "function" && eachTime();
if (test()) {
clearInterval(timer);
sharedTimer && clearInterval(sharedTimer);
action();
}
}, tryInterval || 50);
return timer;
}
// Examples:
// To test this, we'll start with g === 1 and then increment g slowly over a matter of seconds
var g = 1;
var timer2 = setInterval(function(){console.log("incrementing g..."); g++;},750);
// Do something when g is === to an expected value
var timer = waitUntil(ifGEquals7,doSomething,100,timer2);
function ifGEquals7 () {
return g === 7;
}
function doSomething () {
console.log ("g === 7");
}
// Do something on initial load AND whenever the history stack changes
var sharedTimer = waitUntil(sidebarExists,injectSidebar,tryInterval);
$(window).bind("popstate", function() {
waitUntil(sidebarExists,injectSidebar,100,sharedTimer);
});
function sidebarExists() {
return($('.y3').length === 0);
}
function injectSidebar() {
processMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment