I need a progress bar in a for loop in javascript
for(index=0; index < 1000; index++){
// set progress bar value to index/1000 * 100 + '%'
}
I notice we can put it in a setInterval
function, but it will cost more time to run the for loop.
So is there any way to run the for loop and generate the progress bar without cost more time?
Mostly no (see below for why "mostly"), you have to yield back to the browser (e.g., via
setTimeout
orsetInterval
) so it can update the page display, and that will indeed increase the amount of time the loop runs. Now, typically if you use a timeout of0
, browsers will call you back in between 5 and 10 milliseconds. So call it 10ms. In your 1,000-cycle loop, you might yield every 100 cycles (e.g., 10 progress updates), which would only add 100ms or so to the total time.FWIW, that looks like this (let's say it's an array you're looping through):
Use:
Why "mostly" no: On some browsers (not, notably, IE9 or earlier), for some tasks, you could use web workers. A web worker is an isolated JavaScript thread, separate from the main JavaScript thread, which runs in the background. The two threads communicate by posting messages to each other.
So you could fire up a web worker, hand it the work, and have it post you messages to update your progress bar. This article gives the basics of web workers, if you want to go that route.
For what it's worth, it looks something like this:
Main document and script:
counter.js
web-worker script (they're always separate files):