Skip to content

Commit

Permalink
init documentation for cancelAnimationFrame() and `requestAnimation…
Browse files Browse the repository at this point in the history
…Frame()` of `DedicatedWorkerGlobalScope` interface (mdn#30880)

* init

* update example

* update list

* style pretty

* update additional info

* Apply suggestions from code review

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* remove extra comment

* update see also section

* Apply suggestions from code review

* update

* Apply suggestions from code review

Co-authored-by: Jean-Yves Perrier <[email protected]>

* update

* update worker

* better reflect confuse

* update

* update content

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: Jean-Yves Perrier <[email protected]>

* Update files/en-us/web/api/dedicatedworkerglobalscope/cancelanimationframe/index.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

Co-authored-by: skyclouds2001 <[email protected]>

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

Co-authored-by: skyclouds2001 <[email protected]>

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

* Update files/en-us/web/api/dedicatedworkerglobalscope/cancelanimationframe/index.md

* Update files/en-us/web/api/dedicatedworkerglobalscope/cancelanimationframe/index.md

* Update files/en-us/web/api/dedicatedworkerglobalscope/cancelanimationframe/index.md

* Update files/en-us/web/api/dedicatedworkerglobalscope/requestanimationframe/index.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jean-Yves Perrier <[email protected]>
  • Loading branch information
3 people authored and dipikabh committed Jan 17, 2024
1 parent 702d094 commit 70b6c67
Show file tree
Hide file tree
Showing 5 changed files with 212 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: "DedicatedWorkerGlobalScope: cancelAnimationFrame() method"
short-title: cancelAnimationFrame()
slug: Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame
page-type: web-api-instance-method
browser-compat: api.DedicatedWorkerGlobalScope.cancelAnimationFrame
---

{{APIRef}}

The **`cancelAnimationFrame()`** method of the {{domxref("DedicatedWorkerGlobalScope")}} interface cancels an animation frame request previously scheduled through a call to {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}}.

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

## Syntax

```js-nolint
cancelAnimationFrame(handle)
```

### Parameters

- `handle`
- : The ID value returned by a call to {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}}; the call must have been made in the same worker.

### Return value

None ({{jsxref("undefined")}}).

### Exceptions

- `NotSupportedError` {{domxref("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 {{HTMLElement("canvas")}} element to an {{domxref("OffscreenCanvas")}}, using {{domxref("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

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()")}}
- {{domxref("Window.cancelAnimationFrame()")}}
4 changes: 4 additions & 0 deletions files/en-us/web/api/dedicatedworkerglobalscope/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ _This interface inherits methods from the {{domxref("WorkerGlobalScope")}} inter
- : Discards any tasks queued in the `WorkerGlobalScope`'s event loop, effectively closing this particular scope.
- {{domxref("DedicatedWorkerGlobalScope.postMessage()")}}
- : Sends a message — which can consist of `any` JavaScript object — to the parent document that first spawned the worker.
- {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()")}}
- : Cancels an animation frame request previously scheduled through a call to {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}}.
- {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()")}}
- : Perform an animation frame request and call a user-supplied callback function before the next repaint.

## Events

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
---
title: "DedicatedWorkerGlobalScope: requestAnimationFrame() method"
short-title: requestAnimationFrame()
slug: Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame
page-type: web-api-instance-method
browser-compat: api.DedicatedWorkerGlobalScope.requestAnimationFrame
---

{{APIRef}}

The **`requestAnimationFrame()`** method of the {{domxref("DedicatedWorkerGlobalScope")}} interface tells the browser you wish to perform an animation frame request and call a user-supplied callback function before the next repaint.

The frequency of calls to the callback function will generally match the display refresh rate. The most common refresh rate is 60 Hz, (60 cycles/frames per second), though 75 Hz, 120 Hz, and 144 Hz are also widely used. `requestAnimationFrame()` calls are paused in most browsers when running in background tabs or hidden {{HTMLElement("iframe")}}s, to improve performance and battery life.

A call to the `requestAnimationFrame()` method schedules only one single call to the callback function. If you want to animate another frame, your callback function must call `requestAnimationFrame()` again.

> **Warning:** Be sure always to use the first argument (or some other method for getting the current time) to calculate how much the animation will progress in a frame — **otherwise, the animation will run faster on high refresh-rate screens**. For ways to do that, see the examples below.
Calling the `requestAnimationFrame()` method requires the current worker to have an associated owner {{domxref("Window", "window")}}. That means that the current worker must be created by {{domxref("Window", "window")}} or by a dedicated worker that also has an associated owner {{domxref("Window", "window")}}.

## Syntax

```js-nolint
requestAnimationFrame(callback)
```

### Parameters

- `callback`
- The function to call when it's time to update your animation for the next repaint. This callback function is passed a single argument: a {{domxref("DOMHighResTimeStamp")}} indicating the end time of the previous frame's rendering (based on the number of milliseconds since [time origin](/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)).
- The timestamp is a decimal number, in milliseconds, but with a minimal precision of 1 millisecond. The timestamp value is also similar to calling {{domxref('performance.now()')}} at the start of the callback function, but it is never the same value.
- When multiple callbacks queued by `requestAnimationFrame()` begin to fire in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload.

### Return value

A `long` integer value that is the request ID uniquely identifying the entry
in the callback list. This is a non-zero value, but you may not make any other
assumptions about it. You can pass this value to
{{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()", "cancelAnimationFrame()")}} to cancel the refresh callback request, the cancel action must have been made in the same worker.

### Exceptions

- `NotSupportedError` {{domxref("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 {{HTMLElement("canvas")}} element to an {{domxref("OffscreenCanvas")}}, using {{domxref("HTMLCanvasElement.transferControlToOffscreen()")}}, then send a message to the worker to `"start"` its work 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

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()")}}
- {{domxref("Window.requestAnimationFrame()")}}
3 changes: 2 additions & 1 deletion files/en-us/web/api/window/cancelanimationframe/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,5 @@ cancelAnimationFrame(myReq);

## See also

- {{domxref("window.requestAnimationFrame()")}}
- {{domxref("Window.requestAnimationFrame()")}}
- {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()")}}
3 changes: 1 addition & 2 deletions files/en-us/web/api/window/requestanimationframe/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ function animate() {
## See also

- {{domxref("Window.cancelAnimationFrame()")}}
- {{domxref("OffscreenCanvas")}}
- [DedicatedWorkerGlobalScope](/en-US/docs/Web/API/DedicatedWorkerGlobalScope)
- {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()")}}
- [requestAnimationFrame for smart animating](https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/) - Blog post
- [Animating with JavaScript: from setInterval to requestAnimationFrame](https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/) - Blog post
- [TestUFO: Test your web browser for requestAnimationFrame() Timing Deviations](https://www.testufo.com/#test=animation-time-graph)

0 comments on commit 70b6c67

Please sign in to comment.