Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating a div with requestAnimationFrame

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?

like image 761
Adarsh Konchady Avatar asked Apr 19 '26 07:04

Adarsh Konchady


1 Answers

Most functions in JavaScript are synchronous(will execute sequentially). But with asynchronous functions(which will not wait for earlier function to finish), use callbacks to 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>

Fiddle Demo

like image 199
Rayon Avatar answered Apr 21 '26 19:04

Rayon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!