Design & Download
Your JS Library
in Seconds!!!

Snippet: tryUntil() - Try Until It Works

Written by Christopher West (cwest) on October 20, 2017.
Keeps trying to execute a function until it has success or until the timeout is reached.
function tryUntil(fn, opt_timeout, opt_interval) {
  var start = new Date, iteration = 0, self = this;
  opt_timeout = opt_timeout == undefined ? Infinity : opt_timeout;
  opt_interval = opt_interval == undefined ? 100 : opt_interval;
  function fnWrapper() {
    try {
      fn.call(self, ++iteration);
      return true;
    }
    catch (e) {
      if (new Date - start < opt_timeout) {
        setTimeout(fnWrapper, opt_interval);
      }
      return false;
    }
  }
  return fnWrapper();
}