# Updating progress bar animation

The general idea is is a progress bar that updates the totals and percentage continually.

This just gets a bit choppy when I trigger a few of these independently on the same page. I'm doing a bit of math at every step, and wonder if there is a better way to accomplish this.

$bar.animate({width:percent+"%"}, { duration : o.time, easing : 'swing', complete : function() {$amount.text('$'+amount.toFixed(2));$diff.text('$'+(o.max - amount).toFixed(2));$percent.text(Math.floor(percent));
},
step : function(now, fx) {
var actual_amount = (now / 100) * o.max;
$percent.text(Math.floor(now));$amount.text('$'+actual_amount.toFixed(2));$diff.text('$'+(o.max - actual_amount).toFixed(2)); if (o.warning.warning !== 0) { if (now > o.warning.alert) {$bar.css("background-color", o.alert_color);
}
else if (now > o.warning.warning) {
$bar.css("background-color", o.warning_color); } else {$bar.css("background-color", beginning_color);
}
}
},
});


Whenever the above code gets rerun you're re-instantiating those functions. So the first thing I would recommend is to define the callbacks outside of the immediate scope of whatever's re-running it so they only get instantiated once.

// In a galaxy not so far away…
var animationComplete = function() {
$amount.text('$'+amount.toFixed(2));
$diff.text('$'+(o.max - amount).toFixed(2));
$percent.text(Math.floor(percent)); }, animationStep = function(now, fx) { … }; // meanwhile, back at the farm…$bar.animate({width:percent+"%"}, {
duration : o.time,
easing   : 'swing',
complete : animationComplete,
step : animationStep // Got rid of a trailing comma here…
});


Without more context it's hard to say what else you can get away with. You could truncate all your values toFixed(2) early, which would simplify the math for very fractional numbers, but probably not enough for anyone to notice. If, at an earlier point you multiply all your numbers by 100, then you could deal entirely with integers, but there could be some output formatting constraints that make that hard.

All that said, it's likely your animation jitters have nothing to do with the performance of the above JavaScript. You might see some small gains by using CSS transitions and animations instead, which theoretically allow the browser to take better advantage of graphics hardware. (You can still trigger the actual css value changes with JavaScript.)

• Appreciate the input, I attempted the CSS transition/animation route, but there really is no way to have a step callback, and i didn't notice the animations smooth out at all. Also, my step callback needs access to some "private variables as a part of a larger object. – jondavidjohn Dec 7 '11 at 17:08
• +1 for mentioning CSS transitions. They improve performance a lot on most new smartphones. – Attila O. Dec 9 '11 at 21:23