Last active
August 29, 2015 14:19
-
-
Save mike-north/36f7fc9780801946b3a2 to your computer and use it in GitHub Desktop.
Run code upon arrival of DOM elements, when you have no event to listen for
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Poll for presence of DOM elements until they | |
* are found (or until timeout is reached), and then | |
* call a function as soon as a non-empty result is found | |
* | |
* @param {string} selector CSS selector to check for | |
* @param {Function} fn callback function(jqSelector, elapsedTimeInMs) {} | |
* @param {int} timeout timeout in ms (optional) | |
* @param {int} interval polling interval in ms (optional) | |
*/ | |
function runWhenArrived (selector, fn, timeout, interval) { | |
var _interval = interval || 10; //ms | |
var _timeout = timeout || 3000; //ms | |
var maxIterations = _timeout/_interval; | |
var ct = 0; | |
var task = null; | |
var check = function () { | |
ct++; | |
if (ct > maxIterations) { | |
// Taking too long! pull the plug | |
fn(null, _interval); | |
clearInterval(task); | |
} | |
else { | |
// See if our selector is returning non-empty results | |
var $jq = $(selector); | |
if ($jq.length > 0) { | |
// Found something! | |
fn($jq, ct * _interval); // Do the work | |
clearInterval(task); // All done. no need to keep trying | |
} | |
} | |
}; | |
task = setInterval(check, _interval); | |
return task; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found this useful for tweaking Qunit's test runner UI after it finishes loading and setting its self up.
Example usage: