Home > OS >  Refreshing progressbar in js
Refreshing progressbar in js

Time:09-11

Hi, im working on a progress bar in java script and i need it to reset it after it hits 100%. Going infinetly.

function start(al) {
    var bar = document.getElementById('progressBar');
    bar.value = al;
    al  ;
    var sim = setTimeout("start("   al   ")", 1);
    if (al == 100) {
      bar.value = 100;
      clearTimeout(sim);
    }
  }
  var amountLoaded = 0;

This works only if the page is refreshed. But it doesnt work automaticly.

CodePudding user response:

You should use setInterval to call your callback function that handles incrementing the progressbar.

If you want to reset the progressbar after an amount of time, you can use setTimeout to do so.

Here's a live demo that increments the progressbar by 10 every 500ms and once it reaches 100% the setTimeout method is used to reset the elemnt to 0 after 2s from hitting 100%:

/** that function will automatically get executed (called an IIFE) */
(function start() {
  const bar = document.getElementById('progressBar'),
    percentage = document.getElementById('percentage')
  interval = setInterval(() => {
    /** tells whether the progress bar will be full after this iteration */
    const done = bar.value   10 > 100;
    /** add 10 to the value */
    bar.value  = 10;
    percentage.textContent = (done ? 100 : bar.value)   '%';
    /** 100% reached */
    if (done) {
      /** clear the interval so the callback function will no longer be called */
      clearInterval(interval);
      percentage.textContent = 'Resetting in 2 seconds...';
      /** add a 2s delay till resetting the progressbar */
      const timeOut = setTimeout(() => {
        bar.value = 0;
        percentage.textContent = '0%';
        clearTimeout(timeOut);
      }, 2000);
    }
  }, 500); /** the callback is invoked every 500ms */
})();
<progress id="progressBar" max="100" value="0"></progress>
<span id="percentage">0%</span>

You can play around it and apply the values and/or conditions that suits you.

CodePudding user response:

Using setTimeout with a string instead of using a callback is bad practice because it calls eval (making it a security risk) and is less readable. Also, instead of recursively calling start from your timeout callback, you can just use setInterval. From there you may increment your bar.value and check if the value is more than or equal to 100 to call clearInterval. Here, I used short circuiting for cleaner code, but you can expand it out to an if statement if you prefer.

function start(initialValue) {
    const bar = document.getElementById('progessBar');
    bar.value = initialValue;
    const sim = setInterval(() =>   bar.value >= 100 && clearInterval(sim), 1);
}
  • Related