Reputation: 4183
I have a number (float) lets say 4.37. at some point this number is changed to another value that can be basically anthing, but still float and with 2 commas. What i need is a nice transition from the first number to the second one. In particular i am searching for way to display this like this:
from number A it starts growing quickly, and as soon as it gets near the second one it slows down. It should go from number A to B in about 0.8 seconds.
This number is displayed in a DIV.
Upvotes: 2
Views: 938
Reputation: 66404
Here is an example using sine for the curve
function genFactory(a, b, n) { // n is number of steps
var dif = b - a,
pi2 = Math.PI / 2, // sin(Pi/2) === 1
i = 0;
return function () {
if (i === n) return b; // short circuit at the end
return a + dif * Math.sin(pi2 * ++i / n);
};
}
// putting it to use
var a = 4.37, // start point
b = 9.12; // example
// generate function
var f = genFactory(a, b, 100); // 100 steps
// "loop"
var i = window.setInterval( // consider a setTimeout in production code
function () {
var x = f();
if (x === b) window.clearInterval(i);
console.log(x.toFixed(2)); // whatever output
},
800 / 100 // 0.8 seconds over 100 steps
);
Upvotes: 2
Reputation: 318342
You can use jQuery.Animation
for this, and use any easing or animate just about any property
var o = {value : $('#inp1').val};
$.Animation( o, {
value: $('#inp2').val()
}, {
duration: 800,
easing : 'easeOutCubic'
}).progress(function(e) {
$('#result').text((e.tweens[0].now).toFixed(2));
});
Upvotes: 4
Reputation: 46435
There are really two questions here
1) what numbers do I pick as I run from one to another in 0.8 seconds
2) how do I make the updates appear
Now since they eye can't see more than about 20 frames per second (which is why film is 24 fps, and video usually even more), you want about 20 numbers in the transition (0.8 x 24).
Generating these numbers I would recommend you do:
var N=20;
for (i = 0; i < 20 ; i++) {
f = (i/(N-1));
num = low + (high - low) * Math.pow(f, 1/g);
}
As g
gets bigger, the number will "slow down" more as it gets to higher values of i
.
Upvotes: 2