Thank you for your answers, I have been thinking about your suggestions and I have done some more testing.
Example code where errors from play() are handled:
document.addEventListener('DOMContentLoaded', () => {
const videoBox = document.getElementById('video-box');
const video = document.createElement('video');
videoBox.replaceChildren(video);
setInterval(async () => {
try {
await video.play();
} catch (error) {
console.warn("error from play()");
}
}, 1000);
setInterval(() => {
video.load();
}, 2000);
});
It seems to work without warnings. Except when I navigate away from the page and do something else for a few minutes, when I check again I see my warning has been logged a couple times.
Now when I do not await the promise:
document.addEventListener('DOMContentLoaded', () => {
const videoBox = document.getElementById('video-box');
const video = document.createElement('video');
videoBox.replaceChildren(video);
setInterval(async () => {
video.play();
}, 1000);
setInterval(() => {
video.load();
}, 2000);
});
I get the familiar error: Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request.
. But the backtrace points to the line with load(), not play()!
With the call to play() removed completely, I cannot get any error to show up:
document.addEventListener('DOMContentLoaded', () => {
const videoBox = document.getElementById('video-box');
const video = document.createElement('video');
videoBox.replaceChildren(video);
setInterval(() => {
video.load();
}, 2000);
});
This lines up with what @KLASANGUI quoted from the documentation:
Calling load() aborts all ongoing operations involving this media element
The process of aborting any ongoing activities will cause any outstanding Promises returned by play() being fulfilled or rejected as appropriate based on their status before the loading of new media can begin. Pending play promises are aborted with an "AbortError" DOMException.
The backtrace points to load(), which is somewhat confusing. While load() is what triggers the error, the play() method is where the exception is actually raised and needs to be caught. Without a call to play() anywhere, there is no error.
I am inclined to accept @KLASANGUI's answer, but it is the most downvoted one. If you disagree with their answer and my reasoning here, can you explain why?