I've got an element on my page that I would like to increment from time to time:
<p class="count">28</p>
Within my javascript, I have an interval that runs once every 5 seconds and asynchronously grabs the new (higher) number from the server. This functions somewhat along the lines of a counter.
setInterval(function(){
$.post("getcount.php", function(num){
latestNum = num;
});
}, 5000);
If the asynchronous request pulls down the number 56, I would like to see the paragraph text change from 28 to 56, showing many (or most) or the intermediates while it increments. What I'm currently doing is setting another interval to constantly check the paragraph text, and the local variable. If the paragraph text is lower than the variable value, it increments it by 1. It does this every half-a-second.
setInterval(function(){
currNum = Number( $(".count").text() );
if (currNum < latestNum)
$(".count").text( currNum + 1 );
}, 50);
My question is this: Is there a better way to do this without having an interval constantly running? Is this animated-incrementing something I can invoke from the response of an asynchronous request, and then have it cease once the two numbers have met in value? I should note also that there exists the possibility that the next request will take place before the two numbers have been reconciled in value.
How would the collective you do this?