Matt Matt - 9 days ago 7
Javascript Question

Function to animate progress bar based on another function

Given a function with parameters in an array, where the first number is the delay time, and the width property is how much to fill the bar by:

var barFill = new AnimationSequence(bar, [
[100, { width: '10%' }],
[200, { width: '20%' }],
[200, { width: '50%' }],
[200, { width: '80%' }],
[300, { width: '90%' }],
[100, { width: '100%' }]
]);
barFill.animate();


I'm trying to write a function to take those two parameters and animate the filling of the progress bar. So far I have this function:

function AnimationSequence() {
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("label").innerHTML = width * 1 + '%';
}
}
}


This is the current JSFIDDLE: link

Answer

Ok... whats wrong with Your code:

  1. You defined onclick in html - please don't do that. Use JS to attach listeners
  2. You are firing 'showProgress' which doesn't exist
  3. You are using 'new' operator. You should only use it when You want to create new instance of given 'class' (JS has no real classes), and in this case - You just want to execute function.
  4. You are using setInterval when what You really want is setTimeout (or at least I think so)
  5. You want to animate elements without requestAnimationFrame - well it's basically bad idea, but You can do that.

I'm attaching fiddle, which does what You wanted (or at least I think so), but be aware that such a simple thing should have been done with CSS. If You do not care about actual progress of process, and You just want to show user an progress bar, than use CSS transition (I've already done it in snippet), and trigger class which will set width to 100%, on button click.

Theres fiddle for You.

.