play() Rejects DOMException On Interrupt

HTMLMediaElement.play() returns a promise that rejects with named DOMExceptions: AbortError for interruptions and NotAllowedError for autoplay blocks.

TypescriptResilience

Code

typescriptsnippet
17 lines
const video = document.querySelector<HTMLVideoElement>('video');
if (!video) throw new Error('video element missing');

// play() returns a promise: autoplay blocks and interruptions both reject it
try {
  await video.play();
  console.log('playback started');
} catch (error) {
  if (error instanceof DOMException && error.name === 'AbortError') {
    // a pause() or load() call interrupted this request - retry later
    console.log('play interrupted:', error.name);
  } else if (error instanceof DOMException && error.name === 'NotAllowedError') {
    console.log('autoplay blocked until user gesture');
  } else {
    throw error;
  }
}

Inside the snippet

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the Error: bad state stops the flow there instead of continuing.

Top-level bindings video hold the demo state — nothing sits inside a function scope.

Points of care

  • Every symbol it uses is a language built-in — nothing needs fetching.
  • A browser is the runtime here: document are not available in Node.
  • The guard !video cuts the flow short right there using an early throw when its condition holds.

Using it

The file’s steps are announced right in the output: playback started, play interrupted:, autoplay blocked until user gesture.

Key statements

if (!video) throw new Error('video element missing');
await video.play();
throw error;

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
Validation comes first — `Error` marks the failure at `!video`, before any partial work happens.
Does play() Rejects DOMException On Interrupt run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.