Vonder Vonder - 2 months ago 7
Javascript Question

How to increment the progress in javascript progress bar?

I am trying to add a simple javascript progress bar to my website, I found a few scripts, but I always encounter the same problem - I am able to intialize the loader and set it to increment to a given value, but cannot do it in steps. Here is a simple example - https://jsfiddle.net/kimmobrunfeldt/k5v2d0rr/

At the end there is:

bar.animate(1.0);


How can i have it animated in steps? Lets say first to 50% then (after 2 secs) to 75% and then 100%. I've tried

bar.animate(0.5);
bar.animate(0.75);
bar.animate(1);


as well as:

setTimeout(function(){bar.animate(0.5)}, 2000);
setTimeout(function(){bar.animate(0.75)}, 2000);
setTimeout(function(){bar.animate(1)}, 2000);


but it always chooses the last (highest) value, instead of being animated in steps. Any advice appreicated.

Answer
bar.animate(0.5);
bar.animate(0.75);
bar.animate(1);

The above code runs simultaneously, and the last one overrides the others.

setTimeout(function(){bar.animate(0.5); console.log("animate")}, 2000);
    console.log('timeout 1 called');
 setTimeout(function(){bar.animate(0.75); console.log("animate")}, 2000);
    console.log('timeout 2 called');
setTimeout(function(){bar.animate(1); console.log("animate")}, 2000);
    console.log('timeout 3 called');

Soon as the first timeout is set, it doesn't wait for the delay before setting the next. Check the logs on the console to see what happens.

The problem is that those scripts run simultaneously. Do something like this (or something better):

bar.animate(0.5);  // Number from 0.0 to 1.0
setTimeout(function () {
    bar.animate(0.75);
}, 2000);

setTimeout(function () {
    bar.animate(1.0);
}, 4000);

If you wanted to just animate the bar in sequences for the sake of it, you can do keyframes with CSS too.