Search code examples
javascripthtmluser-interfacecommand-line-interfaceprogress-bar

Making a "CLI-like" progress bar in HTML/JS


So I'm working on a command line interface in the web. Currently, there is the start of a progress bar on the left of the CLI, and a few commands that work. I want to add more commands, but I felt that they needed to have a time delay feature to make it feel more authentic.

I want to make a function that, when called, will divide the (ms) used in the scenario by 12 (the number of dashes in the progress bar) and display an update every (ms).

The Progress bar looks something like this: [------------]

https://codepen.io/ZacV/pen/abEYpLz

function statsBar(ms){
  var timeChunk = Math.round(ms/12)
  for (let i = 0; i < timeChunk; i++) {
    document.getElementById("DispStatus").innerHTML = "[" + ("|" * timeChunk) + ("-" * (12 - timeChunk)) + "]"
    sleep(timeChunk);
  }
}

Solution

  • You can use setTimeout to schedule updates to the progress bar all at once but have them happen over time.

    function statsBar(ms){
      var timeChunk = Math.round(ms/12);
      for (let i = 0; i < 12; i++) {
        setTimeout(() => {
          document.getElementById("DispStatus").innerHTML = "[" + ('-'.repeat(i)) + "]";
        }, i * timeChunk);
      }
    }
    statsBar(6000);
    <div id="DispStatus"></div>