Skip to content
Advertisement

How to create multiple Progress Bars called in succession (one after another) using just Vanilla JS on simple HTML + CSS? Without setTimeout

On document load I need three progress bars to run sequentially one after another using Vanilla JS, HTML and CSS. So when the first one finishes loading to completion (it’s max value) the next one fires off. I am not looking for a complicated CSS solution. I am curious to know how to do this with just vanilla JS without a setTimeout approach.

I created this on jsfiddle https://jsfiddle.net/blitzr/vf78hu0g/3/

 <div>
      <label>Bar 1</label>
      <progress class="progressBars" value="0" max = "90"></progress>
      
      <br>
      
      <label>Bar 2</label>
      <progress class="progressBars" value="0" max = "35"></progress>
      
      <br>
      
      <label>Bar 3</label>
      <progress class="progressBars" value="0" max = "35"></progress>
      
      <br>

</div>

I am showing how I would approach one progress bar.

var index = 0;
var id;

let bars = document.getElementsByClassName(`progressBars`);

this.id = setInterval(() => {
  increaseProgress(bars[this.index])    
}, 10 );


function increaseProgress(bar) {
  if (bar.value < bar.max) bar.value++;
  else {
    clearInterval(this.id);
  }
}

With the following css

progress {
  width: 500px;
}
progress::-webkit-progress-bar{
  background-color: gray;
}
progress::-webkit-progress-value{
  background-color: green;
}

Advertisement

Answer

You can write a function that starts an interval timer for a particular bar within your bars HTMLCollection. The function can accept an index representing which bar to start the progress for, and will then use setInterval() to update the value of that particular progress bar. When the bar is full, you can clear your interval, and then re-call your function again with the index of the next bar in your collection, which would be at index+1. Before you run your function you can also check that bar is defined as eventually an index will be passed that doesn’t exist in your HTMLCollection bars:

const bars = document.getElementsByClassName('progressBars');

function startProgress(bars, index = 0) {
  const bar = bars[index];
  if (!bar) return;

  const id = setInterval(() => {
    if (bar.value < bar.max) bar.value++;
    else {
      clearInterval(id);
      startProgress(bars, index + 1);
    }
  }, 10);
}

startProgress(bars);
<label>Bar 1</label>
<progress class="progressBars" value="0" max="90"></progress>
<br />

<label>Bar 2</label>
<progress class="progressBars" value="0" max="35"></progress>
<br />

<label>Bar 3</label>
<progress class="progressBars" value="0" max="35"></progress>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement