Animate A Value Over A Specific Time Period
I thought creating a function that animates a value from a to b in x second was not that difficult but i guess i was wrong or maybe im just tired, anyways how can i do that in jav
Solution 1:
You can do that with setInterval
of setTimeout
javascript methods.
let varToChange = 0;
const amount = 100;
const time = 2;
functionchangeValueOverTime(amount, time) {
setTimeout(function(){
varToChange++;
console.log("varToChange : "+varToChange);
varToChange !== amount ? changeValueOverTime(amount,time) : console.log("done");
},(time*1000)/amount)
}
changeValueOverTime(amount,time);
Solution 2:
Firstly, varToChange
shouldn't be declared with const
if you expect to mutate it. Secondly, use setTimeout
.
let varToChange = 0;
const amount = 100;
const time = 2;
functionchangeValueOverTime(amount, time) {
setTimeout(() => {
varToChange = amount;
}, time * 1000);
}
changeValueOverTime(amount, time);
setTimeout(() => {
console.log(varToChange);
}, 3000);
The second setTimeout
is there so you can see the updated value of varToChange
Solution 3:
here is the function that i made in playcode, maybe i should have clarified that the function should be accurate, this function always returns the exact amount after the given time.
/**
* @example
* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {
* valueToChange = changeValueOverTimeHelper(sub, retrunValues);
* });
* @param intevalTime Rate of Change in Milliseconds
* @param time Time to finish in Milliseconds
* @param amount amount that gets added or subtracted from the `initialValue`
* @param initialVaule Initial Value.
*/
function changeValueOverTime(intevalTime: number, time: number, amount: number, initialVaule: number): Observable < [number, boolean, number] > {
const change = (amount /time) * intevalTime;
const initialDate = new Date();
return rxjs.interval(intevalTime).pipe(
rxjs.operators.map(() => [
initialVaule + (change * (new Date().getTime() - initialDate.getTime())) / intevalTime,
new Date().getTime() - initialDate.getTime() >= time ? true : false,
initialVaule + (change * time) / intevalTime
])
);
}
/**
* @example
* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {
* valueToChange = changeValueOverTimeHelper(sub, retrunValues);
* });
* @param subscipton Subscription to unsubscribe from when``returnValues[1]`` is `true`
*/
function changeValueOverTimeHelper(subscipton: Subscription, returnValues: [number, boolean, number]): number {
if (returnValues[1] === true) {
subscipton.unsubscribe();
return returnValues[2];
} else {
return returnValues[0];
}
}
const sub = this.changeValueOverTime(5, 1000, 100, 0).subscribe(retrunValues => {
console.log(changeValueOverTimeHelper(sub, retrunValues));
});
Post a Comment for "Animate A Value Over A Specific Time Period"