15,908,634 members
See more:
I want a number in a element to gradually reach a value of a variable.

JavaScript
```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.
Posted
Updated 13-May-23 22:15pm
v2
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.

## Solution 1

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
0.5```
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.

v2
Better yet, replace `setInterval` with calls to requestAnimationFrame[^], and use the timestamp argument to calculate what the current value should be. :)