WindowTimers.setInterval(func, delay[, param1, param2, ...])
The parameter 3 rd and further in setInterval are optional parameters for transition to the interval function. Please note: these optional arguments are not supported in IE9 and earlier.
We can use this to our advantage, avoiding the use of a global or external sphere. as shown below. The interval function monitors the limit and current increment of the counter via the opts parameter.
The runTask function takes a mandatory argument fn , which returns a boolean value to determine if a timer has been completed. In the example below, there are two tixes, each of which depends on the speed with which they are running and the state that should be running.
The first two tasks complete, but the last ends with attempts before the condition is met.
function writeLine(el, text) { el.innerHTML += [].slice.call(arguments, 1).join(' ') + '\n'; } function runTask(options, interval, limit) { var interval = setInterval(function(opts) { opts.incr = (opts.incr || 0) + 1; if (opts.fn(opts)) { clearInterval(interval); writeLine(opts.el, '>> Task finished...'); } else if (opts.incr > limit) { clearInterval(interval); writeLine(opts.el, '>> Exceeded limit of ' + limit); } else { writeLine(opts.el, '>> Attempt: ' + opts.incr + '/' + limit); } }, interval, options); }
.col { display: inline-block; width: 175px; font-family: monospace; white-space: pre; border: thin solid black; vertical-align: top; padding: 4px; }
<div class="col"></div> <div class="col"></div> <div class="col"></div>
Mr. Polywhirl
source share