I am trying to animate a div horizontally first and then vertically. But the problem using requestAnimationFrame is that it is doing both animations at once, making the div travel diagonally.
Here is the fiddle link: https://jsfiddle.net/akonchady/z4qmkuyc/22/
What am I doing wrong?
Note: It works as expected if I give a timeout for the second invocation as follows:
animate('abc', 'marginLeft', 250, 1000);
setTimeout(function() {
animate('abc', 'marginTop', 250, 1000);
}, 3000);
However I want to avoid the timeout. How can I achieve this just using requestAnimationFrame?
Most
functionsin JavaScript are synchronous(will execute sequentially). But withasynchronousfunctions(which will not wait for earlier function to finish), usecallbacksto control the flow of the execution.
To invoke send function when first one is done with the animation, use callback
function animate(id, styleAttr, finalValue, duration, callback) {
var ele = document.getElementById('abc'),
startTime = +new Date, //Not sure how readable this is ?
delta = null,
req = null;
(function timeout() {
elapsedTime = +new Date - startTime;
if (elapsedTime >= duration) {
cancelAnimationFrame(req);
ele.style[styleAttr] = finalValue + 'px';
if (typeof callback !== 'undefined') {
callback();
}
return;
} else {
delta = finalValue / duration;
ele.style[styleAttr] = delta * elapsedTime + 'px';
}
req = requestAnimationFrame(timeout);
})();
}
animate('abc', 'marginLeft', 250, 1000, function() {
animate('abc', 'marginTop', 250, 1000);
});
#abc {
width: 100px;
height: 100px;
background-color: red;
}
<div id='abc'>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With