Click here to Skip to main content
15,908,634 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want a number in a element to gradually reach a value of a variable.

setInterval(function() {
  var1 += var2;
  document.getElementById("var1display").innerHTML = var1
        }, 1000)

I have this so far, but I don't want the display to instantly snap to var1 every 1 second, I want it to gradually reach var1 within the time of 1 second.

What I have tried:

I have tried to divide var1 by 1000, and then make it update every 1 millisecond, but that just made var1display go up really fast.
Updated 13-May-23 22:15pm
G Schulz 13-May-23 22:23pm    
Did you try dividing var2 by 1000?
Damifidy 13-May-23 22:29pm    
I have tried, it did not work.
Richard MacCutchan 14-May-23 3:07am    
The only way to do that is to use a timer and update the element each time the timer ticks.

1 solution

Basically, you want ro increase it at a slow rate - a millisecond is way too fast as you get 1000 of them each second!

Since your monitor probably runs at 60 or 75Hz, so that's as fast as it can change the image - 60 or 75 times per second.

So set your interval to a maximum of 1/60th or 1/75th of a second: I'd probably go with maybe 50 milliseconds (or 20Hz) and increment the number by a small interval. How small? That's easy to work out:
(final value - start value) / (update frequency in Hz * the number of seconds you want it to take)
So if you want a number to climb from 0 to 100 in 10 seconds, you'd increase it by:
(100 - 0) / (20 * 10)
100 / 200
If you want integer rises, then you tweak the values to use an integer increment:
(100 - 0) / (x * 10) = 1
100 = x * 10
x = 10
So you'd set the interval for 10Hz or 100 milliseconds.
Share this answer
Richard Deeming 15-May-23 4:23am    
Better yet, replace setInterval with calls to requestAnimationFrame[^], and use the timestamp argument to calculate what the current value should be. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900