Skip to content

Instantly share code, notes, and snippets.

@mike-north
Last active August 29, 2015 14:19
Show Gist options
  • Save mike-north/36f7fc9780801946b3a2 to your computer and use it in GitHub Desktop.
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
/**
* 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;
};
@mike-north
Copy link
Author

I found this useful for tweaking Qunit's test runner UI after it finishes loading and setting its self up.

Example usage:

runWhenArrived('#qunit-modulefilter', function (ele, elapsedMs) {
  if (ele) {
    // SUCCESS
    console.log('formatted qunit select after ' + elapsedMs + ' ms');
    ele.material_select();
  }
  else {
    // FAIL
    console.log('never found it :(');
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment