requestAnimationFrame() in 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.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 69 | 79 | 99 | 16.4 | 69 | 16.4 | |
| The requestAnimationFrame() method of the DedicatedWorkerGlobalScope interface tells the browser you wish to perform an animation frame request and call a user-supplied callback function before the next repaint. | 69 | 79 | 99 | 16.4 | 69 | 16.4 |
- Not supported in nested Web Workers. See bug 41483010.
- Not supported in nested Web Workers. See bug 41483010.
- Not supported in nested Web Workers. See bug 41483010.
Syntax
const worker = new Worker("worker.js");
// Transfer canvas control to the worker
const offscreenCanvas = document
.querySelector("canvas")
.transferControlToOffscreen();
// Start the animation
worker.postMessage(
{
type: "start",
canvas: offscreenCanvas,
},
[offscreenCanvas],
);
// Stop the animation after 5 seconds
setTimeout(() => {
worker.postMessage({
type: "stop",
});
}, 5000); Use cases
-
Using requestAnimationFrame() in workers
The cancelAnimationFrame() method of the DedicatedWorkerGlobalScope interface cancels an animation frame request previously scheduled through a call to requestAnimationFrame().
Cautions
- May not be supported in older browsers.
Implementation notes
- Some APIs require a secure context (HTTPS) or user activation. Check the requirements before use.