Due to the single-threaded nature of Javascript, your setInterval()
callback can't possibly be called before the end of the for
loop, no matter how long it takes to execute.
I'd recommend to do it the other way around: log elapsed time every N iterations.
var res = [],
ts = performance.now();
for(var i = 0, max = 1E6; i < max; i++) {
if(!(i % 10000)) {
res.push(performance.now() - ts);
}
// do something
}
console.log(res);
Or:
var res = [],
ts = performance.now();
for(var i = 0, iMax = 1E6; i < iMax; i += 10000) {
for(var j = i, jMax = Math.min(i + 10000, iMax); j < jMax; j++) {
// do something
}
res.push(performance.now() - ts);
}
console.log(res);
If you really want to log in real time, you'd have to yield control to the browser after each batch of N iterations. Performance wise, this will probably have a significant impact, though.
var res = [],
ts = performance.now();
function processBatch(i, iMax, sz) {
for(var j = i, jMax = Math.min(i + sz, iMax); j < jMax; j++) {
// do something
}
console.log((j * 100 / iMax) + '%', (performance.now() - ts).toFixed(2) + 'ms');
if(j < iMax) {
setTimeout(function() { processBatch(j, iMax, sz); }, 0);
}
}
processBatch(0, 1E6, 10000);
EDIT: This third method was significantly updated. The previous version was erroneous.
initialization
in theloop
setInterval
will get invoked after theduration
, asclearInterval
is obviously invoked before100ms
,callback
is never invoked.