yantrab
yantrab

Reputation: 2652

JavaScript: How to calculate animation duration according to easing?

For example if I have:

el.animate([keyFrame100, keyFrame0], { duration: 600, easing: 'ease-in' });

how can I determine the animation's duration to do something after the animation has finished?

Or, is there a way that I can subscribe to an animation's finish? My use case is that I want to close a dialog after the animation is complete:

setTimeout(() => ref.close(dialogResult), 550);

Upvotes: 1

Views: 358

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

The animate() function returns an instance of Animation when called.

Each Animation instance consists of an onfinish event handler which is fired when the animation itself has completed:

// Store animation object in "animation" variable
const animation = el.animate(
    [keyFrame100, keyFrame0], 
    { 
        duration: 600, 
        easing: 'ease-in' 
    });

// Attach a function that is executed when animation is completed
animation.onfinish = () => {

    // Runs when animation completed
    ref.close(dialogResult)
}

The nice thing about an event driven approach like this is that you need not track the animation's duration to decide when the animation has finished (and in turn, when to run the "finish" code). Instead, we delegate this to the API which internally tracks and determines when to trigger the onfinish event.

Hope that helps!

Upvotes: 2

Related Questions