Design & Download
Your JS Library
in Seconds!!!

Snippet: poll() - Wait for A Condition Before Executing

Written by Christopher West (cwest) on October 20, 2017.
Periodically tests for a condition to be met before executing some code.
function poll(fnTest, fnOnFound, opt_timeout, opt_interval) {
  var isDone, iteration = 0, self = this, start = new Date;
  opt_timeout = opt_timeout == undefined ? Infinity : opt_timeout;
  opt_interval = opt_interval == undefined ? 100 : opt_interval;
  function cancel() {
    isDone = true;
  }
  function fnTestWrapper() {
    try {
      var result = fnTest.call(self, cancel, ++iteration);
      if (result) {
        isDone = result;
        fnOnFound.call(self, result, iteration);
        result;
      }
      return !!result;
    }
    catch (e) {
      throw e;
    }
    finally {
      if (!isDone && (new Date - start) < opt_timeout) {
        setTimeout(fnTestWrapper, opt_interval);
      }
    }
  }
  return fnTestWrapper();
}