简体   繁体   中英

How to monitor a for-loop?

I would like to monitor the content of a for loop every X millisecond:

Here is an example, I expect to see progression percentage every 0.1 seconds :

for (i = 0, max = 9007199254740992, timer = setInterval(function() {console.log(100*i/max);}, 100); i < max; i++) {
  // something
}
clearInterval(timer);

But it does not output anything.

I would like not to add a test in my loop to avoid using useless computation time.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM