Q:

How to make two progress bars onload

I want to make two progress bars working on load. But the code which I write makes only one loading. Also those two progress bars has to be different in length when loaded. I don't want to repeat code, so I am adding arrays. But I am not quite sure that this is the best solution. Maybe in body tag it is possible to write two different functions, or only one can be onload? If it is possible with several functions onload, then the number array shouldnt't be used. My code below. Maybe anyone knows the solution?

<style>
.myProgress {
width: 100%;
background-color: #000000;
}

#myBar1, #myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body onload="move()">

<div class="myProgress">
<div id="myBar1"></div>
</div>

<div class="myProgress">
<div id="myBar2"></div>
</div>

<script>
function move() {
var ids = ["myBar1", "myBar2"];
var number = [60, 90]
var length = ids.length;
for(i = 1; i<=length; i++){
var elem = document.getElementById("myBar"+i);
var width = 1;
var id = setInterval(frame, 10);
function frame() {
    if (width >= number[i-1]) {
    clearInterval(id);
    } else {
    width++; 
    elem.style.width = width + '%'; 
    }
}
}

}
</script>

A:

The problem was caused because you were mixing loops with async operations which usually doesn't turn out well. If you want to do that you should use let instead of var or do the operation in another function. Moreover you can set the width in the html element and read all the progress bars.

function move() {
  for (var item of document.querySelectorAll(".myProgress")) {
    loading(item.firstElementChild, +item.getAttribute("width") || 100); // replace 100 with default
  }
}

function loading(bar, maxWidth) {
  var width = 0;
  var intervalId = setInterval(function() {
    if (width >= maxWidth) clearInterval(intervalId);
    else bar.style.width = ++width + '%';
  }, 10);
}
.myProgress {
  width: 100%;
  background-color: #000000;
}

#myBar1,
#myBar2 {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
<body onload="move()">

  <div class="myProgress" width="60">
    <div id="myBar1"></div>
  </div>

  <div class="myProgress" width="90">
    <div id="myBar2"></div>
  </div>
</body>

