Skip to content

Instantly share code, notes, and snippets.

@simevidas
Forked from AdaRoseCannon/Finished polyfill.js
Last active August 3, 2020 10:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save simevidas/2e721c8e6d67f04b5e1a0083c542a767 to your computer and use it in GitHub Desktop.
Save simevidas/2e721c8e6d67f04b5e1a0083c542a767 to your computer and use it in GitHub Desktop.
Animation.prototype.finished polyfill
// only polyfill .finished in browsers that already support animate()
if (document.body.animate) {
// Chrome does not seem to expose the Animation constructor globally
if (typeof Animation === 'undefined') {
window.Animation = document.body.animate({}).constructor;
}
if (Animation.prototype.finished === undefined) {
Object.defineProperty(Animation.prototype, 'finished', {
get() {
if (!this._finished) {
this._finished = this.playState === 'finished' ?
Promise.resolve() :
new Promise((resolve, reject) => {
this.addEventListener('finish', resolve, {once: true});
this.addEventListener('cancel', reject, {once: true});
});
}
return this._finished;
}
});
}
}
@simevidas
Copy link
Author

simevidas commented Aug 22, 2017

Demo: https://jsbin.com/demokay/edit?js,output; tested in Firefox and Chrome.

Note: This is a fork of Ada Rose’s polyfill. I’ve added support for .catch() (invoked when the animation is aborted), and cleaned up the code a bit.

@AdaRoseCannon
Copy link

Nice!!

@simevidas
Copy link
Author

Also works with await (inside an async function):

try { 
    await animation.finished;    
    // animation finished
} catch (e) {
    // animation aborted
}

Demo: https://jsbin.com/yejanag/edit?js,output

@AdaRoseCannon
Copy link

:D that's how I've been using it in my own code.

Promises and async functions are nice.

@simevidas
Copy link
Author

After adding both the official Web Animations polyfill, and the above finished polyfill, I got the demos working in Edge, too, but there seems to be an issue in iOS Safari, which I’m unable to debug.

@davej
Copy link

davej commented Jul 12, 2019

I was getting an error in Safari 13 (tech preview):

Unhandled Promise Rejection: TypeError: The Animation.finished getter can only be used on instances of Animation

So I forked this to fix the error: https://gist.github.com/davej/23b0481016bcdb969df46423c6284771

image

@simevidas
Copy link
Author

👍 Good to see more (full?) animation API support in the next version of Safari.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment