what i am trying to do is a function that prints out a sequence of numbers (eg. 1-100) in a given time (eg. 2 seconds). super easy.
The hardest part is that the sequence animation should begin slowly and speed up exponentially. This is what i have so far:
var animationLength = 2000; //ms
var counter = 0,
counterEnd = 100,
countInterval = animationLength / counterEnd; // 20ms
function animate() {
$('#result').text(counter++);
if (counter <= counterEnd) {
//Calculate here dynamically newInterval
var newInterval = countInterval;
countInterval = newInterval;
setTimeout(animate, newInterval);
}
}
animate();
So, now countInterval
is constantly 20ms, but it should be variable, decreasing exponentially. Eg:
counter = 1; => countInterval = 40ms //not sure about that
...
counter = 100; => countInterval = 1ms
And the summatory of these intervals has to be 2000ms
https://jsfiddle.net/fvxf7mby/5/
UPDATE:
thanks to @Mats Lind i finally found out. That's the final code (JSFIDDLE)
var animationLength = 2000; //ms
var counter = 0,
counterEnd = 100,
countInterval = animationLength / counterEnd, // 20 ms,
a = 1.05; //speed factor
var summatory = 0;
function animate() {
$('#result').text(counter++);
if (counter <= counterEnd) {
//that's the formula:
var newInterval = (animationLength-summatory) / ( (a - Math.pow(a, -(counterEnd-1))) / (a-1))
summatory += newInterval;
countInterval = newInterval;
setTimeout(animate, newInterval);
} else {
$('#summatory').text(summatory); //should be 2000
}
}
animate();