DedicatedWorkerGlobalScope: cancelAnimationFrame() method

Baseline 2023
Newly available

Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Note: This feature is only available in Dedicated Web Workers.

The cancelAnimationFrame() method of the DedicatedWorkerGlobalScope interface cancels an animation frame request previously scheduled through a call to requestAnimationFrame().

Calling the cancelAnimationFrame() method requires the current worker to have an associated owner window. That means that the current worker must be created by window or by a dedicated worker that also has an associated owner window.

Syntax

js
cancelAnimationFrame(handle)

Parameters

handle

The ID value returned by a call to requestAnimationFrame(); the call must have been made in the same worker.

Return value

None (undefined).

Exceptions

NotSupportedError DOMException

Thrown if the method is not supported by the current worker.

Examples

On the main thread, we start by transferring the control of a <canvas> element to an OffscreenCanvas, using HTMLCanvasElement.transferControlToOffscreen() and send to a message to "start" its work to the worker, with the offscreen canvas:

js
const offscreenCanvas = document
  .querySelector("canvas")
  .transferControlToOffscreen();

worker.postMessage(
  {
    type: "start",
    canvas: offscreenCanvas,
  },
  [offscreenCanvas],
);

When receiving the "start" message, the worker starts the animation, moving the rectangle from left to right. Upon reception of a "stop" message, it will stop the animation.

js
let ctx;
let pos = 0;

function draw(dt) {
  ctx.clearRect(0, 0, 100, 100);
  ctx.fillRect(pos, 0, 10, 10);
  pos += 10 * dt;
  self.requestAnimationFrame(draw);
}

self.addEventListener("message", (e) => {
  if (e.data.type === "start") {
    const transferredCanvas = e.data.canvas;
    ctx = transferredCanvas.getContext("2d");
    self.requestAnimationFrame(draw);
  }
  if (e.data.type === "stop") {
    self.cancelAnimationFrame(handle);
  }
});

Finally, if needed, the main thread can send a "stop" message to the worker to stop the animation:

js
worker.postMessage({
  type: "stop",
});

Specifications

Specification
HTML
# animationframeprovider-cancelanimationframe

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
cancelAnimationFrame

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

See also