1

I'm trying to do a progress bar so that the users can know when will their file be downloaded. I don't know what I did wrong, but the progress bar style doesn't update in the for loop.

var filesize = 1000 //this is not the final value 
var progressbar = document.getElementById("progress");
function myFunction(){
  for(var i = 0; i <= filesize; i++){
    x = i/ filesize * 100;
    x = parseInt(x.toString().slice(0, 3));
    console.log(x + "%")
    progressbar.style.width = x + "%";
  }
}
#bar{
    width: 35%;
    background-color: rgba(0,0,0,0.17);
    border-radius: 130px;
    margin: auto;
  }
  #progress{
    width: 0%;
    height: 30px;
    background-color: rgb(255, 0, 0);
    border-radius: 130px;
  }
    <button onclick="myFunction()">Click me</button>
    <div id="bar">
      <div id="progress"></div>
    </div>

2
  • 2
    you may use setInterval and setTimeout for your progress representation! Commented Apr 11, 2020 at 18:40
  • Not able to reproduce your problem - it runs OK for me in FF and Chrome (albeit too fast to really see the progress changes). Maybe try slowing it down, with @Ebrahim's suggestions? Commented Apr 11, 2020 at 18:48

1 Answer 1

1

You can make the progress bar move smoothly by adding the transition property in CSS.

A higher transition time will result in the progress bar moving slower.

var filesize = 1000 //this is not the final value 
var progressbar = document.getElementById("progress");
function myFunction() {
  for (var i = 0; i <= filesize; i++) {
    x = i/ filesize * 100;
    x = parseInt(x.toString().slice(0, 3));
    console.log(x + "%")
    progressbar.style.width = x + "%";
  }
}
#bar {
  width: 35%;
  background-color: rgba(0,0,0,0.17);
  border-radius: 130px;
  margin: auto;
}
   
#progress {
  width: 0%;
  height: 30px;
  background-color: rgb(255, 0, 0);
  border-radius: 130px;
  transition: 0.2s;
}
<button onclick="myFunction()">Click me</button>
  <div id="bar">
    <div id="progress">
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.