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);
}
// 5 atttempts to reach 4 in 250ms.
runTask({
fn : function(opts) { return opts.incr === 4; },
el : document.querySelectorAll('div.col')[0]
}, 250, 5);
// 10 atttempts to reach 7 in 100ms.
runTask({
fn : function(opts) { return opts.incr === 7; },
el : document.querySelectorAll('div.col')[1]
}, 100, 10);
// 10 atttempts to reach 15 in 50ms.
runTask({
fn : function(opts) { return opts.incr === 15; },
el : document.querySelectorAll('div.col')[2]
}, 50, 10);
.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>