Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Created June 9, 2012 00:19
Show Gist options
  • Save shawndumas/2898791 to your computer and use it in GitHub Desktop.
Save shawndumas/2898791 to your computer and use it in GitHub Desktop.
WaitUntil...
// Play with it here --> http://jsfiddle.net/Pdft8/2/
Function.waitUntil = function(fn, condition, interval, stopOnReady) {
var defaults = {
pageReady: function() {
return (/complete|loaded|interactive/).test(document.readyState);
},
pageLoad: function() {
return (/complete|loaded/).test(document.readyState);
}
};
interval = interval || 100;
condition = (typeof condition === 'function') ?
condition :
defaults[condition || 'pageLoad'];
(function() {
var timer = setInterval(
function() {
var check = false,
ready = defaults['pageReady'](),
loaded = defaults['pageLoad'](),
stop = (stopOnReady === true && ready) ||
(stopOnReady === false && loaded);
try { check = !!(condition()); } catch (e) { }
if (check || stop) {
clearInterval(timer);
fn();
}
},
interval
);
})();
};
Function.waitUntil(
// the code you want to wait on running here...
function() {
document.getElementById('result').innerHTML = 'I waited...';
},
// the function that tests for a condition here...
// or, instead of a function, you can put the strings
// 'pageReady' or 'pageLoad' to run at those times respectively
function() {
return !!(document.getElementById('result'));
},
// amount to wait between checks
100,
// true to stop invoking condition on page ready,
// false to stop on page loaded,
// undefined (un-passed) to only stop on condition returning true
true
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment