0

I have an animation that when one part is finished the other is started and it can be very long queue.

I put the code here: https://jsfiddle.net/homa/qub7ejd1/

As you can see to have the queue, I have this code:

newMessage('HA HA HA HA ....').onfinish = function () {
    newMessage('Don\'t tell anybody I am here....').onfinish = function () {
        newMessage('<b>PLEAAAASEEE</b>').onfinish = function () {
            newMessage('I was very hungry...').onfinish = function () {
                newMessage('Hello');
            }
        }
    }

};

My code gets really really ugly as it gradually gets long. Also when I have if else to run a specific animation in queue, it hardly is readable.

Do you have any suggestion to solve this problem?

Homa
  • 3,417
  • 2
  • 19
  • 24

1 Answers1

0

You can use Promises instead of call backs. An example here, as you can see the second animation (blue box) run after the first animation (red box) has been finished:

https://jsfiddle.net/gibbok/mw23dmzf/

The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never. More info here.

A related interesting article could be found here:

http://danielcwilson.com/blog/2016/03/animations-and-promises/

var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var animate1 = function() {
  return animation1 = box1.animate([{
    left: '0px'
  }, {
    left: '100px'
  }], 1000);
};
var animate2 = function() {
  return animation2 = box2.animate([{
    top: '150px'
  }, {
    top: '250px'
  }], 1000);
};

function canceledHandler() {
  console.log('animation1 canceled: ' + Date.now());
}
animate1().finished.then(animate2, canceledHandler);
GibboK
  • 71,848
  • 143
  • 435
  • 658