Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  40] [ 1]  / answers: 1 / hits: 103130  / 11 Years ago, sat, june 8, 2013, 12:00:00

I am updating a numeric value inside an element by doing intervalled ajax requests.



To make the whole thing a bit more alive, I want to count from the current value to the new one, by partially in- or decreasing the value over a time of n sec.



So basically something like this:



<div id=value>100</div>
<script type=text/javascript>
/** Decrease $value (over a time of 2 seconds) till it reaches 25 */
$value.increaseAnimation(-75, {duration:2});
</script>


Is there a javascript library for doing so?


More From » css

 Answers
18

You can just code it yourself pretty simply:




function animateValue(id, start, end, duration) {
if (start === end) return;
var range = end - start;
var current = start;
var increment = end > start? 1 : -1;
var stepTime = Math.abs(Math.floor(duration / range));
var obj = document.getElementById(id);
var timer = setInterval(function() {
current += increment;
obj.innerHTML = current;
if (current == end) {
clearInterval(timer);
}
}, stepTime);
}

animateValue(value, 100, 25, 5000);

#value {
font-size: 50px;
}

<div id=value>100</div>






Here's is a more accurate version that self adjusts in case the timer intervals aren't perfectly accurate (which they sometimes aren't):




function animateValue(id, start, end, duration) {
// assumes integer values for start and end

var obj = document.getElementById(id);
var range = end - start;
// no timer shorter than 50ms (not really visible any way)
var minTimer = 50;
// calc step time to show all interediate values
var stepTime = Math.abs(Math.floor(duration / range));

// never go below minTimer
stepTime = Math.max(stepTime, minTimer);

// get current time and calculate desired end time
var startTime = new Date().getTime();
var endTime = startTime + duration;
var timer;

function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = value;
if (value == end) {
clearInterval(timer);
}
}

timer = setInterval(run, stepTime);
run();
}

animateValue(value, 100, 25, 5000);

#value {
font-size: 50px;
}

<div id=value>100</div>




[#77745] Thursday, June 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;