A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame below:

DedicatedWorkerGlobalScope: cancelAnimationFrame() method - Web APIs

DedicatedWorkerGlobalScope: cancelAnimationFrame() method

Baseline 2023

Newly available

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
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:

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.

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:

worker.postMessage({
  type: "stop",
});
Specifications Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4