javascriptanimation

What is the simplest way of chaining together animations using promises?


I'm trying to chain together a few animations created with the requestAnimationFrame method (no jQuery used). Because of the way requestAnimationFrame is implemented, timing the successive animations with setTimeout doesn't produce the desired result. Hence, I'm attempting to accomplish my objective using promises.

As a JavaScript tyro, I'm still struggling a bit with this whole promise concept. Could someone please tell me why the (admittedly naive) approach taken below doesn't work? Many thanks in advance!

var animation1 = function(){
    var promise = Promise.resolve();
    var t = 0;
    var runAnimation = function(){
        if (t < endValue) {
            t++; 
            // do animation stuff
            requestAnimationFrame(runAnimation)
        }
        else{return promise}
    }
    runAnimation();
}

var animation2 = function(){
    var promise = Promise.resolve();
    var t = 0;
    var runAnimation = function(){
        if (t < endValue) { 
            t++;
            // do animation stuff
            requestAnimationFrame(runAnimation)
        }
        else{return promise}
    }
    runAnimation();
}    

animation1().then(animation2());

Solution

  • You need to return a Promise from the function

    var animation1 = function(){
        return new Promise(function(resolve) {
          var t = 0;
          var runAnimation = function(){
              if (t < endValue) {
                  t++; 
                  // do animation stuff
                  requestAnimationFrame(runAnimation)
              }
              else{resolve()}
          };
    
          runAnimation();
       });
    }
    

    Same for animation2

    And chaining should look like this

    animation1().then(animation2) //<-- pass function not the result of its invocation