简体   繁体   中英

Update progress bar in with javascript

I want to update my progress bar in html while function is running. Is there any way I can do this?

function animateProgressBar() {
  var numIteration = 100;

  for (var i = 1; i <= numIteration; i++) {
    //do some calculations
    width = (i/numIteration)*100;
    htmlElement.style.width = width + '%'; 
  }
}

The problem is that your code is blocking. Therefore the page isnt rendered, and the status bar doesnt change. You may use a setTimeout recursively:

function animateProgressBar(numIteration,index=1) {
    width = (index/numIteration)*100;
    htmlElement.style.width = width + '%'; 
    if(index<numIteration) setTimeout(animateProgressBar,100,numIteration,index+1);
} 

Start like this:

animateProgressBar(100); // from 1 to 100

Note that index=1 in the parameters is ES6, so just use it on modern browsers...

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