Hey everyone!
(and hello to some old friends!)
tl;dr:
Q: If you want to change the src of a media tag before the previous play()'s Promise has resolved, is it best practice to simply catch the exception?
Full background:
I am implementing something that plays ambient audio for different "scenes." Here's a simplified demo:
My demo works fine with a fast enough internet connection, but if you:
1. Open Chrome DevTools -> Network tab -> check disable cache and simulate Fast 3G (
screenshot)
2. Click the "play" button
3. Then click "next scene!" a few times quickly (
screenshot)
There's an (expected) exception thrown: "Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.
https://goo.gl/LdLk22"
This makes sense, because I'm changing the src and calling play() before the previous play() Promise has resolved, and I believe what's happening is that in
step 3 of load(), all pending play Promises are rejected.
The
DevRel article linked suggests waiting for the previous play() Promise to be resolved, but that doesn't apply to my situation because I actually *don't* want to load or play any part of e.g. Scene 2's audio if the user has clicked into Scene 3 before Scene 2's audio loaded.
So what I've done instead is this:
audioElement.play().catch((e) => {
if (e.code === DOMException.ABORT_ERR) {
console.log('previous play() was aborted, which is fine');
return;
}
// Unexpected exception - rethrow.
throw e;
});
i.e. I just catch the exception and ignore it...
Is that best practice for this scenario, or is there a better way to effectively cancel the previous load? Or am I approaching this in the wrong way?
Thanks everyone!
Victoria