setInterval() global function - Web APIs

setInterval() global function
=============================

**Note:** This feature is available in Web Workers

The **`setInterval()`** method, offered on the `Window` and `WorkerGlobalScope` interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`.

Syntax
------

```js
setInterval(code)
setInterval(code, delay)

setInterval(func)
setInterval(func, delay)
setInterval(func, delay, arg1)
setInterval(func, delay, arg1, arg2)
setInterval(func, delay, arg1, arg2, /\* …, \*/ argN)
```

### Parameters

`func`

A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds.

`code`

 An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds.
 This syntax is *not recommended* for the same reasons that make using `eval()` a security risk.

`delay` Optional

 The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified.
 See Delay restrictions below for details on the permitted range of `delay` values.

`arg1`, …,`argN` Optional

Additional arguments which are passed through to the function specified by *func* once the timer expires.

### Return value

The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval.

 It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably.
 For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

**Note:** The `delay` argument is converted to a signed 32-bit integer.
 This effectively limits `delay` to 2147483647 ms, since it's specified as a signed integer in the IDL.

Examples
--------

### Example 1: Basic syntax

The following example demonstrates `setInterval()`'s basic syntax.

```js
const intervalID = setInterval(myCallback, 500, "Parameter 1", "Parameter 2");

function myCallback(a, b) {
  // Your code here
  // Parameters are purely optional.
  console.log(a);
  console.log(b);
}
```

### Example 2: Alternating two colors

 The following example calls the `flashtext()` function once a second until
 the Stop button is pressed.

#### HTML

```html
<div id="my\_box">
  <h3>Hello World</h3>
</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
```

#### CSS

```css
.go {
  color: green;
}
.stop {
  color: red;
}
```

#### JavaScript

```js
// variable to store our intervalID
let nIntervId;

function changeColor() {
  // check if an interval has already been set up
  if (!nIntervId) {
    nIntervId = setInterval(flashText, 1000);
  }
}

function flashText() {
  const oElem = document.getElementById("my\_box");
  oElem.className = oElem.className === "go" ? "stop" : "go";
}

function stopTextColor() {
  clearInterval(nIntervId);
  // release our intervalID from the variable
  nIntervId = null;
}

document.getElementById("start").addEventListener("click", changeColor);
document.getElementById("stop").addEventListener("click", stopTextColor);
```

#### Result

See also: `clearInterval()`.

The "this" problem
------------------

 When you pass a method to `setInterval()` or any other function, it is invoked with the wrong `this` value.
 This problem is explained in detail in the JavaScript reference.

### Explanation

 Code executed by `setInterval()` runs in a separate execution context than
 the function from which it was called. As a consequence, the `this`
 keyword for the called function is set to the `window` (or
 `global`) object, it is not the same as the `this` value for the
 function that called `setTimeout`. See the following example (which uses
 `setTimeout()` instead of `setInterval()` – the problem, in fact,
 is the same for both timers):

```js
myArray = ["zero", "one", "two"];

myArray.myMethod = function (sProperty) {
  alert(arguments.length > 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds

// Passing the 'this' object with .call won't work
// because this will change the value of this inside setTimeout itself
// while we want to change the value of this inside myArray.myMethod.
// In fact, it will be an error because setTimeout code expects this to be the window object:
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS\_ERROR\_XPC\_BAD\_OP\_ON\_WN\_PROTO: Illegal operation on WrappedNative prototype object"
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
```

 As you can see there are no ways to pass the `this` object to the callback
 function in the legacy JavaScript.

### A possible solution

All modern JavaScript runtimes (in browsers and elsewhere) support arrow functions, with lexical `this` — allowing us to write `setInterval(() => this.myMethod())` if we're inside the `myArray` method.

If you need to support IE, use the `Function.prototype.bind()` method, which lets you specify the value that should be used as `this` for all calls to a given function. That lets you easily bypass problems where it's unclear what `this` will be, depending on the context from which your function was called.

Usage notes
-----------

 The `setInterval()` function is commonly used to set a delay for functions
 that are executed again and again, such as animations. You can cancel the interval using
 `clearInterval()`.

 If you wish to have your function called *once* after the specified delay, use
 `setTimeout()`.

### Delay restrictions

 It's possible for intervals to be nested; that is, the callback for
 `setInterval()` can in turn call `setInterval()` to start another
 interval running, even though the first one is still going. To mitigate the potential
 impact this can have on performance, once intervals are nested beyond five levels deep,
 the browser will automatically enforce a 4 ms minimum value for the interval. Attempts
 to specify a value less than 4 ms in deeply-nested calls to `setInterval()`
 will be pinned to 4 ms.

 Browsers may enforce even more stringent minimum values for the interval under some
 circumstances, although these should not be common. Note also that the actual amount of
 time that elapses between calls to the callback may be longer than the given
 `delay`; see
 Reasons for delays longer than specified for examples.

### Ensure that execution duration is shorter than interval frequency

 If there is a possibility that your logic could take longer to execute than the
 interval time, it is recommended that you recursively call a named function using
 `setTimeout()`. For example, if
 using `setInterval()` to poll a remote server every 5 seconds, network
 latency, an unresponsive server, and a host of other issues could prevent the request
 from completing in its allotted time. As such, you may find yourself with queued up XHR
 requests that won't necessarily return in order.

In these cases, a recursive `setTimeout()` pattern is preferred:

```js
(function loop() {
  setTimeout(() => {
    // Your logic here

    loop();
  }, delay);
})();
```

 In the above snippet, a named function `loop()` is declared and is
 immediately executed. `loop()` is recursively called inside
 `setTimeout()` after the logic has completed executing. While this pattern
 does not guarantee execution on a fixed interval, it does guarantee that the previous
 interval has completed before recursing.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-setinterval-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `setInterval` which allows passing arguments to the callback in `core-js`
* `setTimeout()`
* `clearTimeout()`
* `clearInterval()`
* `window.requestAnimationFrame()`


HTMLTableSectionElement - Web APIs

HTMLTableSectionElement
=======================

The **`HTMLTableSectionElement`** interface provides special properties and methods (beyond the `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies (`<thead>`, `<tfoot>`, and `<tbody>`, respectively) in an HTML table.

EventTarget

Node

Element

HTMLElement

HTMLTableSectionElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLTableSectionElement.align`
Deprecated

A string containing an enumerated value reflecting the `align` attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

`HTMLTableSectionElement.rows` Read only

Returns a live `HTMLCollection` containing the rows in the section. The `HTMLCollection` is live and is automatically updated when rows are added or removed.

`HTMLTableSectionElement.ch`
Deprecated

A string containing one single character. This character is the one to align all the cell of a column on. It reflects the `char` and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

`HTMLTableSectionElement.chOff`
Deprecated

A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableRowElement.ch`. This property was optional and was not very well supported.

`HTMLTableSectionElement.vAlign`
Deprecated

A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the `valign` attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`.

Instance methods
----------------

*Inherits methods from its parent, `HTMLElement`*.

`HTMLTableSectionElement.deleteRow()`

Removes the row, corresponding to the `index` given in parameter, in the section. If the `index` value is `-1` the last row is removed; if it smaller than `-1` or greater than the amount of rows in the collection, a `DOMException` with the value `IndexSizeError` is raised.

`HTMLTableSectionElement.insertRow()`

Returns an `HTMLTableRowElement` representing a new row of the section. It inserts it in the rows collection immediately before the `<tr>` element at the given `index` position. If the `index` is `-1`, the new row is appended to the collection. If the `index` is smaller than `-1` or greater than the number of rows in the collection, a `DOMException` with the value `IndexSizeError` is raised.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmltablesectionelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML elements implementing this interface: `<tfoot>`, `<thead>`, and `<tbody>`.


HTMLAreaElement - Web APIs

HTMLAreaElement
===============

The **`HTMLAreaElement`** interface provides special properties and methods (beyond those of the regular object `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of `<area>` elements.

EventTarget

Node

Element

HTMLElement

HTMLAreaElementInstance properties
-------------------

*Inherits properties from its parent `HTMLElement`.*

`HTMLAreaElement.alt`

A string that reflects the `alt` HTML attribute, containing alternative text for the element.

`HTMLAreaElement.coords`

A string that reflects the `coords` HTML attribute, containing coordinates to define the hot-spot region.

`HTMLAreaElement.download`

A string indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it.

`HTMLAreaElement.hash`

A string containing the fragment identifier (including the leading hash mark (#)), if any, in the referenced URL.

`HTMLAreaElement.host`

A string containing the hostname and port (if it's not the default port) in the referenced URL.

`HTMLAreaElement.hostname`

A string containing the hostname in the referenced URL.

`HTMLAreaElement.href`

A string containing that reflects the `href` HTML attribute, containing a valid URL of a linked resource.

`HTMLAreaElement.noHref`
Deprecated

A boolean flag indicating if the area is inactive (`true`) or active (`false`).

`HTMLAreaElement.origin` Read only

Returns a string containing the origin of the URL, that is its scheme, its domain and its port.

`HTMLAreaElement.password`

A string containing the password specified before the domain name.

`HTMLAreaElement.pathname`

A string containing the path name component, if any, of the referenced URL.

`HTMLAreaElement.port`

A string containing the port component, if any, of the referenced URL.

`HTMLAreaElement.protocol`

A string containing the protocol component (including trailing colon `':'`), of the referenced URL.

`HTMLAreaElement.referrerPolicy`

A string that reflects the `referrerpolicy` HTML attribute indicating which referrer to use when fetching the linked resource.

`HTMLAreaElement.rel`

A string that reflects the `rel` HTML attribute, indicating relationships of the current document to the linked resource.

`HTMLAreaElement.relList` Read only

Returns a `DOMTokenList` that reflects the `rel` HTML attribute, indicating relationships of the current document to the linked resource, as a list of tokens.

`HTMLAreaElement.search`

A string containing the search element (including leading question mark `'?'`), if any, of the referenced URL.

`HTMLAreaElement.shape`

A string that reflects the `shape` HTML attribute, indicating the shape of the hot-spot, limited to known values.

`HTMLAreaElement.target`

A string that reflects the `target` HTML attribute, indicating the browsing context in which to open the linked resource.

`HTMLAreaElement.username`

A string containing the username specified before the domain name.

Instance methods
----------------

*Inherits methods from its parent, `HTMLElement`.*

`HTMLAreaElement.toString()`

Returns a string containing the whole URL. It is a synonym for `HTMLAreaElement.href`.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlareaelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML element implementing this interface: `<area>`


GPUAdapterInfo - Web APIs

GPUAdapterInfo
==============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`GPUAdapterInfo`** interface of the WebGPU API contains identifying information about a `GPUAdapter`.

A `GPUAdapterInfo` object instance is requested using the `GPUAdapter.requestAdapterInfo()` method.

Instance properties
-------------------

`architecture`
Experimental
 Read only

The name of the family or class of GPUs the adapter belongs to. Returns an empty string if it is not available.

`description`
Experimental
 Read only

A human-readable string describing the adapter. Returns an empty string if it is not available.

`device`
Experimental
 Read only

A vendor-specific identifier for the adapter. Returns an empty string if it is not available.

`vendor`
Experimental
 Read only

The name of the adapter vendor. Returns an empty string if it is not available.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterInfo = await adapter.requestAdapterInfo();
  console.log(adapterInfo.architecture);
  console.log(adapterInfo.vendor);

  // ...
}
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # gpu-adapterinfo |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


WebGLBuffer - Web APIs

WebGLBuffer
===========

The **WebGLBuffer** interface is part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors.

WebGLObject

WebGLBufferDescription
-----------

The `WebGLBuffer` object does not define any methods or properties of its own and its content is not directly accessible. When working with `WebGLBuffer` objects, the following methods of the `WebGLRenderingContext` are useful:

* `WebGLRenderingContext.bindBuffer()`
* `WebGLRenderingContext.createBuffer()`
* `WebGLRenderingContext.deleteBuffer()`
* `WebGLRenderingContext.isBuffer()`
Examples
--------

### Creating a buffer

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
const buffer = gl.createBuffer();
```

Specifications
--------------

| Specification |
| --- |
| WebGL Specification # 5.4 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebGLRenderingContext.bindBuffer()`
* `WebGLRenderingContext.createBuffer()`
* `WebGLRenderingContext.deleteBuffer()`
* `WebGLRenderingContext.isBuffer()`
* Other buffers: `WebGLFramebuffer`, `WebGLRenderbuffer`


Battery Status API - Web APIs

Battery Status API
==================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **Battery Status API**, more often referred to as the **Battery API**, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss.

**Note:** This API is *not available* in Web Workers (not exposed via `WorkerNavigator`).

Interfaces
----------

`BatteryManager`

Provides information about the system's battery charge level.

### Extensions to other interfaces

`Navigator.getBattery()`

Returns a `Promise` that resolves with a `BatteryManager` object.

Example
-------

In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the `chargingchange`, `levelchange`, `chargingtimechange`, `dischargingtimechange` events.

```js
navigator.getBattery().then((battery) => {
  function updateAllBatteryInfo() {
    updateChargeInfo();
    updateLevelInfo();
    updateChargingInfo();
    updateDischargingInfo();
  }
  updateAllBatteryInfo();

  battery.addEventListener("chargingchange", () => {
    updateChargeInfo();
  });
  function updateChargeInfo() {
    console.log(`Battery charging? ${battery.charging ? "Yes" : "No"}`);
  }

  battery.addEventListener("levelchange", () => {
    updateLevelInfo();
  });
  function updateLevelInfo() {
    console.log(`Battery level: ${battery.level \* 100}%`);
  }

  battery.addEventListener("chargingtimechange", () => {
    updateChargingInfo();
  });
  function updateChargingInfo() {
    console.log(`Battery charging time: ${battery.chargingTime} seconds`);
  }

  battery.addEventListener("dischargingtimechange", () => {
    updateDischargingInfo();
  });
  function updateDischargingInfo() {
    console.log(`Battery discharging time: ${battery.dischargingTime} seconds`);
  }
});
```

See also the example in the specification.

Specifications
--------------

| Specification |
| --- |
| Battery Status API  |

Browser compatibility
---------------------

### api.BatteryManager

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.Navigator.getBattery

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Hacks blog post - Using the Battery API


setTimeout() global function - Web APIs

setTimeout() global function
============================

**Note:** This feature is available in Web Workers

 The global **`setTimeout()`** method sets a timer which executes a function or specified
 piece of code once the timer expires.

Syntax
------

```js
setTimeout(code)
setTimeout(code, delay)

setTimeout(functionRef)
setTimeout(functionRef, delay)
setTimeout(functionRef, delay, param1)
setTimeout(functionRef, delay, param1, param2)
setTimeout(functionRef, delay, param1, param2, /\* …, \*/ paramN)
```

### Parameters

`functionRef`

A `function` to be executed after the timer expires.

`code`

 An alternative syntax that allows you to include a string instead of a function,
 which is compiled and executed when the timer expires. This syntax is **not
recommended** for the same reasons that make using
 `eval()` a security risk.

`delay` Optional

 The time, in milliseconds that the timer should wait before
 the specified function or code is executed. If this parameter is omitted, a value of 0
 is used, meaning execute "immediately", or more accurately, the next event cycle.

Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.

Also note that if the value isn't a number, implicit type coercion is silently done on the value to convert it to a number — which can lead to unexpected and surprising results; see Non-number delay values are silently coerced into numbers for an example.

`param1`, …, `paramN` Optional

 Additional arguments which are passed through to the function specified by
 `functionRef`.

### Return value

 The returned `timeoutID` is a positive integer value which
 identifies the timer created by the call to `setTimeout()`. This value can be
 passed to `clearTimeout()` to
 cancel the timeout.

 It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to
 `setTimeout()` or `setInterval()` on the same object (a window or
 a worker). However, different objects use separate pools of IDs.

Description
-----------

 Timeouts are cancelled using
 `clearTimeout()`.

 To call a function repeatedly (e.g., every *N* milliseconds), consider using
 `setInterval()`.

### Non-number delay values are silently coerced into numbers

If `setTimeout()` is called with *delay* value that's not a number, implicit type coercion is silently done on the value to convert it to a number. For example, the following code incorrectly uses the string `"1000"` for the *delay* value, rather than the number `1000` – but it nevertheless works, because when the code runs, the string is coerced into the number `1000`, and so the code executes 1 second later.

```js
setTimeout(() => {
  console.log("Delayed for 1 second.");
}, "1000");
```

But in many cases, the implicit type coercion can lead to unexpected and surprising results. For example, when the following code runs, the string `"1 second"` ultimately gets coerced into the number `0` — and so, the code executes immediately, with zero delay.

```js
setTimeout(() => {
  console.log("Delayed for 1 second.");
}, "1 second");
```

Therefore, don't use strings for the *delay* value but instead always use numbers:

```js
setTimeout(() => {
  console.log("Delayed for 1 second.");
}, 1000);
```

### Working with asynchronous functions

`setTimeout()` is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.
 In other words, you cannot use `setTimeout()` to create a "pause" before the next function in the function stack fires.

See the following example:

```js
setTimeout(() => {
  console.log("this is the first message");
}, 5000);
setTimeout(() => {
  console.log("this is the second message");
}, 3000);
setTimeout(() => {
  console.log("this is the third message");
}, 1000);

// Output:

// this is the third message
// this is the second message
// this is the first message
```

 Notice that the first function does not create a 5-second "pause" before calling the second function. Instead, the first function is called, but waits 5 seconds to
 execute. While the first function is waiting to execute, the second function is called, and a 3-second wait is applied to the second function before it executes. Since neither
 the first nor the second function's timers have completed, the third function is called and completes its execution first. Then the second follows. Then finally the first function
 is executed after its timer finally completes.

To create a progression in which one function only fires after the completion of another function, see the documentation on Promises.

### The "this" problem

 When you pass a method to `setTimeout()`, it will be invoked with a `this` value that may differ from your
 expectation. The general issue is explained in detail in the JavaScript reference.

 Code executed by `setTimeout()` is called from an execution context separate
 from the function from which `setTimeout` was called. The usual rules for
 setting the `this` keyword for the called function apply, and if you have not
 set `this` in the call or with `bind`, it will default to
 the `window` (or `global`) object. It will not be the same as the
 `this` value for the function that called `setTimeout`.

See the following example:

```js
const myArray = ["zero", "one", "two"];
myArray.myMethod = function (sProperty) {
  console.log(arguments.length > 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
```

 The above works because when `myMethod` is called, its `this` is
 set to `myArray` by the call, so within the function,
 `this[sProperty]` is equivalent to `myArray[sProperty]`. However,
 in the following:

```js
setTimeout(myArray.myMethod, 1.0 \* 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1.5 \* 1000, "1"); // prints "undefined" after 1.5 seconds
```

 The `myArray.myMethod` function is passed to `setTimeout`, then
 when it's called, its `this` is not set, so it defaults to the
 `window` object.

 There's also no option to pass a `thisArg` to
 `setTimeout` as there is in Array methods such as `forEach()` and `reduce()`. As shown below,
 using `call` to set `this` doesn't work either.

```js
setTimeout.call(myArray, myArray.myMethod, 2.0 \* 1000); // error
setTimeout.call(myArray, myArray.myMethod, 2.5 \* 1000, 2); // same error
```

#### Solutions

##### Use a wrapper function

 A common way to solve the problem is to use a wrapper function that sets
 `this` to the required value:

```js
setTimeout(function () {
  myArray.myMethod();
}, 2.0 \* 1000); // prints "zero,one,two" after 2 seconds
setTimeout(function () {
  myArray.myMethod("1");
}, 2.5 \* 1000); // prints "one" after 2.5 seconds
```

The wrapper function can be an arrow function:

```js
setTimeout(() => {
  myArray.myMethod();
}, 2.0 \* 1000); // prints "zero,one,two" after 2 seconds
setTimeout(() => {
  myArray.myMethod("1");
}, 2.5 \* 1000); // prints "one" after 2.5 seconds
```

##### Use bind()

Alternatively, you can use `bind()` to set the value of `this` for all calls to a given function:

```js
const myArray = ["zero", "one", "two"];
const myBoundMethod = function (sProperty) {
  console.log(arguments.length > 0 ? this[sProperty] : this);
}.bind(myArray);

myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
myBoundMethod(1); // prints "one"
setTimeout(myBoundMethod, 1.0 \* 1000); // still prints "zero,one,two" after 1 second because of the binding
setTimeout(myBoundMethod, 1.5 \* 1000, "1"); // prints "one" after 1.5 seconds
```

### Passing string literals

 Passing a string instead of a function to `setTimeout()` has the same problems as using
 `eval()`.

```js
// Don't do this
setTimeout("console.log('Hello World!');", 500);
```

```js
// Do this instead
setTimeout(() => {
  console.log("Hello World!");
}, 500);
```

A string passed to `setTimeout()` is evaluated in the global context, so local symbols in the context where `setTimeout()` was called will not be available when the string is evaluated as code.

### Reasons for delays longer than specified

 There are a number of reasons why a timeout may take longer to fire than anticipated.
 This section describes the most common reasons.

#### Nested timeouts

 As specified in the HTML standard,
 browsers will enforce a minimum timeout of 4 milliseconds once a nested call to `setTimeout` has been scheduled 5 times.

 This can be seen in the following example, in which we nest a call to `setTimeout` with a delay of `0` milliseconds,
 and log the delay each time the handler is called. The first four times, the delay is approximately 0 milliseconds, and after that it is
 approximately 4 milliseconds:

```html
<button id="run">Run</button>
<table>
  <thead>
    <tr>
      <th>Previous</th>
      <th>This</th>
      <th>Actual delay</th>
    </tr>
  </thead>
  <tbody id="log"></tbody>
</table>
```

```js
let last = 0;
let iterations = 10;

function timeout() {
  // log the time of this call
  logline(new Date().getMilliseconds());
  // if we are not finished, schedule the next call
  if (iterations-- > 0) {
    setTimeout(timeout, 0);
  }
}

function run() {
  // clear the log
  const log = document.querySelector("#log");
  while (log.lastElementChild) {
    log.removeChild(log.lastElementChild);
  }

  // initialize iteration count and the starting timestamp
  iterations = 10;
  last = new Date().getMilliseconds();
  // start timer
  setTimeout(timeout, 0);
}

function logline(now) {
  // log the last timestamp, the new timestamp, and the difference
  const tableBody = document.getElementById("log");
  const logRow = tableBody.insertRow();
  logRow.insertCell().textContent = last;
  logRow.insertCell().textContent = now;
  logRow.insertCell().textContent = now - last;
  last = now;
}

document.querySelector("#run").addEventListener("click", run);
```

```
\* {
  font-family: monospace;
}
th,
td {
  padding: 0 10px 0 10px;
  text-align: center;
  border: 1px solid;
}
table {
  border-collapse: collapse;
  margin-top: 10px;
}
```

#### Timeouts in inactive tabs

 To reduce the load (and associated battery usage) from background tabs, browsers will enforce
 a minimum timeout delay in inactive tabs. It may also be waived if a page is playing sound
 using a Web Audio API `AudioContext`.

The specifics of this are browser-dependent:

* Firefox Desktop and Chrome both have a minimum timeout of 1 second for inactive tabs.
* Firefox for Android has a minimum timeout of 15 minutes for inactive tabs and may unload them entirely.
* Firefox does not throttle inactive tabs if the tab contains an `AudioContext`.

#### Throttling of tracking scripts

 Firefox enforces additional throttling for scripts that it recognizes as tracking scripts.
 When running in the foreground, the throttling minimum delay is still 4ms. In background tabs, however,
 the throttling minimum delay is 10,000 ms, or 10 seconds, which comes into effect 30 seconds after a
 document has first loaded.

 See Tracking Protection for
 more details.

#### Late timeouts

 The timeout can also fire later than expected if the page (or the OS/browser) is busy with other tasks.
 One important case to note is that the function or code snippet cannot be executed until
 the thread that called `setTimeout()` has terminated. For example:

```js
function foo() {
  console.log("foo has been called");
}
setTimeout(foo, 0);
console.log("After setTimeout");
```

Will write to the console:
```

After setTimeout
foo has been called
```

 This is because even though `setTimeout` was called with a delay of zero,
 it's placed on a queue and scheduled to run at the next opportunity; not immediately.
 Currently-executing code must complete before functions on the queue are executed, thus
 the resulting execution order may not be as expected.

#### Deferral of timeouts during pageload

 Firefox will defer firing `setTimeout()` timers
 while the current tab is loading. Firing is deferred until the main thread is deemed
 idle (similar to window.requestIdleCallback()),
 or until the load event is fired.

### WebExtension background pages and timers

 In WebExtensions, `setTimeout()`
 does not work reliably. Extension authors should use the `alarms`
 API instead.

### Maximum delay value

 Browsers store the delay as a 32-bit signed integer internally. This causes an integer
 overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in
 the timeout being executed immediately.

Examples
--------

### Setting and clearing timeouts

 The following example sets up two simple buttons in a web page and hooks them to the
 `setTimeout()` and `clearTimeout()` routines. Pressing the first
 button will set a timeout which shows a message after two seconds and stores the
 timeout id for use by `clearTimeout()`. You may optionally cancel this
 timeout by pressing on the second button.

#### HTML

```html
<button onclick="delayedMessage();">Show a message after two seconds</button>
<button onclick="clearMessage();">Cancel message before it happens</button>

<div id="output"></div>
```

#### JavaScript

```js
let timeoutID;

function setOutput(outputContent) {
  document.querySelector("#output").textContent = outputContent;
}

function delayedMessage() {
  setOutput("");
  timeoutID = setTimeout(setOutput, 2 \* 1000, "That was really slow!");
}

function clearMessage() {
  clearTimeout(timeoutID);
}
```

```
#output {
  padding: 0.5rem 0;
}
```

#### Result

See also the `clearTimeout()` example.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-settimeout-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `setTimeout` which allows passing arguments to the callback in `core-js`
* `clearTimeout`
* `setInterval()`
* `window.requestAnimationFrame`
* `queueMicrotask()`


TaskAttributionTiming - Web APIs

TaskAttributionTiming
=====================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`TaskAttributionTiming`** interface returns information about the work involved in a long task and its associate frame context. The frame context, also called the container, is the iframe, embed or object that is being implicated, on the whole, for a long task.

You usually work with `TaskAttributionTiming` objects when observing long tasks.

`TaskAttributionTiming` inherits from `PerformanceEntry`.

PerformanceEntry

TaskAttributionTimingInstance properties
-------------------

This interface extends the following `PerformanceEntry` properties for event timing performance entry types by qualifying them as follows:

`PerformanceEntry.duration` Read only
Experimental

Always returns `0`, as `duration` is not applicable for this interface.

`PerformanceEntry.entryType` Read only
Experimental

Always returns `taskattribution`.

`PerformanceEntry.name` Read only
Experimental

Always returns `"unknown"`.

`PerformanceEntry.startTime` Read only
Experimental

Always returns `0`.

This interface also supports the following properties:

`TaskAttributionTiming.containerType` Read only
Experimental

Returns the type of frame container, one of `iframe`, `embed`, or `object`.

`TaskAttributionTiming.containerSrc` Read only
Experimental

Returns the container's `src` attribute.

`TaskAttributionTiming.containerId` Read only
Experimental

Returns the container's `id` attribute.

`TaskAttributionTiming.containerName` Read only
Experimental

Returns the container's `name` attribute.

Instance methods
----------------

`TaskAttributionTiming.toJSON()`
Experimental

Returns a JSON representation of the `TaskAttributionTiming` object.

Specifications
--------------

| Specification |
| --- |
| Long Tasks API # sec-TaskAttributionTiming |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `PerformanceLongTaskTiming`


Presentation - Web APIs

Presentation
============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`Presentation`** can be defined as two possible user agents in the context: *Controlling user agent* and *Receiving user agent*.

In controlling browsing context, the `Presentation` interface provides a mechanism to override the browser default behavior of launching presentation to external screen. In receiving browsing context, `Presentation` interface provides the access to the available presentation connections.

Instance properties
-------------------

`Presentation.defaultRequest`
Experimental

In a controlling user agent, the `defaultRequest` attribute *MUST* return the default presentation request if any, `null` otherwise. In a receiving browsing context, it *MUST* return `null`.

`Presentation.receiver`
Experimental

In a receiving user agent, the `receiver` attribute *MUST* return the `PresentationReceiver` instance associated with the receiving browsing context and created by the receiving user agent when the receiving browsing context is created.

Instance methods
----------------

None.

Specifications
--------------

| Specification |
| --- |
| Presentation API # interface-presentation |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCRtpCodecParameters - Web APIs

RTCRtpCodecParameters
=====================

The `RTCRtpCodecParameters` dictionary, part of the WebRTC API, is used to describe the configuration parameters for a single media codec.

 It's used in `RTCRtpSender.getParameters()`, `RTCRtpSender.setParameters()` and `RTCRtpReceiver.getParameters()`.
 Its also use used when calling `RTCRtpTransceiver.setCodecPreferences()` to configure a transceiver's codecs before beginning the offer/answer process to establish a WebRTC peer connection.

Most of the fields in this property take values which are defined and maintained by the Internet Assigned Numbers Authority (IANA). References to relevant IANA documents are provided in the see also section at the end of this article.

Instance properties
-------------------

`payloadType` Optional

The RTP payload type used to identify this codec.

`mimeType` Optional

The codec's MIME media type and subtype specified as a string of the form `"type/subtype"`. IANA maintains a registry of valid MIME types.

`clockRate` Optional

An unsigned long integer value specifying the codec's clock rate in hertz (Hz). The clock rate is the rate at which the codec's RTP timestamp advances. Most codecs have specific values or ranges of values they permit; see the IANA payload format media type registry for details.

`channels` Optional

An unsigned short integer indicating the number of channels the codec should support. For example, for audio codecs, a value of 1 specifies monaural sound while 2 indicates stereo.

`sdpFmtpLine` Optional

A string containing the format-specific parameters field from the `"a=fmtp"` line in the codec's SDP, if one is present; see section 5.8 of the IETF specification for JSEP.

**Note:** On an `RTCRtpReceiver`, the format-specific parameters come from the SDP sent by the remote peer, while for `RTCRtpSender`, they're provided by the local description.

See also
--------

Real-Time Transport Protocol (RTP) Parameters

The IANA document providing registries of permitted values for the RTP parameters used by this dictionary.


CSSCounterStyleRule - Web APIs

CSSCounterStyleRule
===================

The **`CSSCounterStyleRule`** interface represents an `@counter-style` at-rule.

CSSRule

CSSCounterStyleRuleInstance properties
-------------------

*This interface also inherits properties from its parent `CSSRule`.*

`CSSCounterStyleRule.name`

A string object that contains the serialization of the `<custom-ident>` defined as the `name` for the associated rule.

`CSSCounterStyleRule.system`

A string object that contains the serialization of the `system` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.symbols`

A string object that contains the serialization of the `symbols` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.additiveSymbols`

A string object that contains the serialization of the `additive-symbols` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.negative`

A string object that contains the serialization of the `negative` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.prefix`

A string object that contains the serialization of the `prefix` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.suffix`

A string object that contains the serialization of the `suffix` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.range`

A string object that contains the serialization of the `range` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.pad`

A string object that contains the serialization of the `pad` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.speakAs`

A string object that contains the serialization of the `speak-as` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

`CSSCounterStyleRule.fallback`

A string object that contains the serialization of the `fallback` descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

Instance methods
----------------

*This interface doesn't implement any specific method but inherits methods from its parent `CSSRule`.*

Specifications
--------------

| Specification |
| --- |
| CSS Counter Styles Level 3 # the-csscounterstylerule-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `@counter-style`
* CSS counter styles module


ConstantSourceNode - Web APIs

ConstantSourceNode
==================

The `ConstantSourceNode` interface—part of the Web Audio API—represents an audio source (based upon `AudioScheduledSourceNode`) whose output is single unchanging value. This makes it useful for cases in which you need a constant value coming in from an audio source. In addition, it can be used like a constructible `AudioParam` by automating the value of its `offset` or by connecting another node to it; see Controlling multiple parameters with ConstantSourceNode.

A `ConstantSourceNode` has no inputs and exactly one monaural (one-channel) output. The output's value is always the same as the value of the `offset` parameter.

EventTarget

AudioNode

AudioScheduledSourceNode

ConstantSourceNode

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |

Constructor
-----------

`ConstantSourceNode()`

Creates and returns a new `ConstantSourceNode` instance, optionally specifying an object which establishes initial values for the object's properties. As an alternative, you can use the `BaseAudioContext.createConstantSource()` factory method; see Creating an AudioNode.

Instance properties
-------------------

*Inherits properties from its parent interface, `AudioScheduledSourceNode`, and adds the following properties:*

`offset`

An `AudioParam` which specifies the value that this source continuously outputs. The default value is 1.0.

### Events

*Inherits events from its parent interface, `AudioScheduledSourceNode`.*

**Note:** Some browsers' implementations of these events are part of the `AudioScheduledSourceNode` interface.

`ended`

Fired whenever the `ConstantSourceNode` data has stopped playing.

Instance methods
----------------

*Inherits methods from its parent interface, `AudioScheduledSourceNode`.*

**Note:** Some browsers' implementations of these methods are part of the `AudioScheduledSourceNode` interface.

`start()`

Schedules a sound to playback at an exact time.

`stop()`

Schedules a sound to stop playback at an exact time.

Example
-------

In the article Controlling multiple parameters with ConstantSourceNode, a `ConstantSourceNode` is created to allow one slider control to change the gain on two `GainNode`s. The three nodes are set up like this:

```js
gainNode2 = context.createGain();
gainNode3 = context.createGain();
gainNode2.gain.value = gainNode3.gain.value = 0.5;
volumeSliderControl.value = gainNode2.gain.value;

constantNode = context.createConstantSource();
constantNode.connect(gainNode2.gain);
constantNode.connect(gainNode3.gain);
constantNode.start();

gainNode2.connect(context.destination);
gainNode3.connect(context.destination);
```

This code starts by creating the gain nodes and setting them and the volume control that will adjust their value all to 0.5. Then the `ConstantSourceNode` is created by calling `AudioContext.createConstantSource()`, and the gain parameters of each of the two gain nodes are connected to the `ConstantSourceNode`. After starting the constant source by calling its `start()` method. Finally, the two gain nodes are connected to the audio destination (typically speakers or headphones).

Now, whenever the value of `constantNode.offset` changes, the gain on both `gainNode2` and `gainNode3` will change to have that same value.

To see this example in action, as well as to read the rest of the code from which these snippets were derived, see Controlling multiple parameters with ConstantSourceNode.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # ConstantSourceNode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API
* `AudioScheduledSourceNode`
* `AudioNode`


Geolocation API - Web APIs

Geolocation API
===============

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **Geolocation API** allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

WebExtensions that wish to use the `Geolocation` object must add the `"geolocation"` permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.

Concepts and usage
------------------

You will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.

The Geolocation API is accessed via a call to `navigator.geolocation`; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).

The developer can now access this location information in a couple of different ways:

* `Geolocation.getCurrentPosition()`: Retrieves the device's current location.
* `Geolocation.watchPosition()`: Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location.

In both cases, the method call takes up to three arguments:

* A mandatory success callback: If the location retrieval is successful, the callback executes with a `GeolocationPosition` object as its only parameter, providing access to the location data.
* An optional error callback: If the location retrieval is unsuccessful, the callback executes with a `GeolocationPositionError` object as its only parameter, providing access information on what went wrong.
* An optional object which provides options for retrieval of the position data.

For further information on Geolocation usage, read Using the Geolocation API.

Interfaces
----------

`Geolocation`

The main class of this API — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch.

`GeolocationPosition`

Represents the position of a user. A `GeolocationPosition` instance is returned by a successful call to one of the methods contained inside `Geolocation`, inside a success callback, and contains a timestamp plus a `GeolocationCoordinates` object instance.

`GeolocationCoordinates`

Represents the coordinates of a user's position; a `GeolocationCoordinates` instance contains latitude, longitude, and other important related information.

`GeolocationPositionError`

A `GeolocationPositionError` is returned by an unsuccessful call to one of the methods contained inside `Geolocation`, inside an error callback, and contains an error code and message.

### Extensions to other interfaces

`Navigator.geolocation`

The entry point into the API. Returns a `Geolocation` object instance, from which all other functionality can be accessed.

Examples
--------

See Using the Geolocation API for example code.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # geolocation\_interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### Availability

As Wi-Fi-based locating is often provided by Google, the vanilla Geolocation API may be unavailable in China. You may use local third-party providers such as Baidu, Autonavi, or Tencent. These services use the user's IP address and/or a local app to provide enhanced positioning.

See also
--------

* Using the Geolocation API
* Geolocation API on w3.org
* Who moved my geolocation? (Hacks blog)


VideoEncoder - Web APIs

VideoEncoder
============

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`VideoEncoder`** interface of the WebCodecs API encodes `VideoFrame` objects into `EncodedVideoChunk`s.

EventTarget

VideoEncoderConstructor
-----------

`VideoEncoder()`

Creates a new `VideoEncoder` object.

Instance properties
-------------------

*Inherits properties from its parent, `EventTarget`.*

`VideoEncoder.encodeQueueSize` Read only

An integer representing the number of encode queue requests.

`VideoEncoder.state` Read only

Represents the state of the underlying codec and whether it is configured for encoding.

### Events

`dequeue`

Fires to signal a decrease in `VideoEncoder.encodeQueueSize`.

Static methods
--------------

`VideoEncoder.isConfigSupported()`

Returns a promise indicating whether the provided `VideoEncoderConfig` is supported.

Instance methods
----------------

*Inherits methods from its parent, `EventTarget`.*

`VideoEncoder.configure()`

Asynchronously prepares the encoder to accept video frames for encoding with the specified parameters.

`VideoEncoder.encode()`

Asynchronously encodes a `VideoFrame`.

`VideoEncoder.flush()`

Returns a promise that resolves once all pending encodes have been completed.

`VideoEncoder.reset()`

Cancels all pending encodes and callbacks.

`VideoEncoder.close()`

Ends all pending work and releases system resources.

Specifications
--------------

| Specification |
| --- |
| WebCodecs # videoencoder-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

Video processing with WebCodecs


PeriodicSyncManager - Web APIs

PeriodicSyncManager
===================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`PeriodicSyncManager`** interface of the Web Periodic Background Synchronization API provides a way to register tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests. Access `PeriodicSyncManager` through the `ServiceWorkerRegistration.periodicSync`.

Instance properties
-------------------

None.

Instance methods
----------------

`PeriodicSyncManager.register()`
Experimental

Registers a periodic sync request with the browser with the specified tag and options. Returns a `Promise` that resolves when the registration completes.

`PeriodicSyncManager.getTags()`
Experimental

Returns a `Promise` that resolves with a list of `strings` representing the tags that are currently registered for periodic syncing.

`PeriodicSyncManager.unregister()`
Experimental

Unregisters the periodic sync request corresponding to the specified tag and returns a `Promise` that resolves when unregistration completes.

Examples
--------

The following examples show how to use the interface.

### Requesting a Periodic Background Sync

The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context:

```js
async function registerPeriodicNewsCheck() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.periodicSync.register("get-latest-news", {
      minInterval: 24 \* 60 \* 60 \* 1000,
    });
  } catch {
    console.log("Periodic Sync could not be registered!");
  }
}
```

### Verifying a Background Periodic Sync by Tag

This code checks to see if a Periodic Background Sync task with a given tag is registered.

```js
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.getTags().then((tags) => {
    if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad();
  });
});
```

### Removing a Periodic Background Sync Task

The following code removes a Periodic Background Sync task to stop articles syncing in the background.

```js
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.unregister("get-latest-news");
});
```

Specifications
--------------

| Specification |
| --- |
| Web Periodic Background Synchronization # periodicsyncmanager-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Richer offline experiences with the Periodic Background Sync API
* A Periodic Background Sync demo app


SpeechRecognitionErrorEvent - Web APIs

SpeechRecognitionErrorEvent
===========================

The **`SpeechRecognitionErrorEvent`** interface of the Web Speech API represents error messages from the recognition service.

Event

SpeechRecognitionErrorEventInstance properties
-------------------

*`SpeechRecognitionErrorEvent` also inherits properties from its parent interface, `Event`.*

`SpeechRecognitionErrorEvent.error` Read only

Returns the type of error raised.

`SpeechRecognitionErrorEvent.message` Read only

Returns a message describing the error in more detail.

Examples
--------

```js
const recognition = new SpeechRecognition();

recognition.onerror = (event) => {
  console.log(`Speech recognition error detected: ${event.error}`);
  console.log(`Additional information: ${event.message}`);
};
```

Specifications
--------------

| Specification |
| --- |
| Web Speech API # speechrecognitionerrorevent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Web Speech API


CSSMathSum - Web APIs

CSSMathSum
==========

The **`CSSMathSum`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the result obtained by calling `add()`, `sub()`, or `toSum()` on `CSSNumericValue`.

A CSSMathSum is the object type returned when the `StylePropertyMapReadOnly.get()` method is used on a CSS property whose value is created with a `calc()` function.

CSSStyleValue

CSSNumericValue

CSSMathValue

CSSMathSumConstructor
-----------

`CSSMathSum()`
Experimental

Creates a new `CSSMathSum` object.

Instance properties
-------------------

`CSSMathSum.values`

Returns a `CSSNumericArray` object which contains one or more `CSSNumericValue` objects.

Static methods
--------------

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

Instance methods
----------------

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

Event handlers
--------------

No

Examples
--------

We create an element with a `width` determined using a `calc()` function, then `console.log()` the `operator` and `values`, and dig into the values a bit.

```html
<div>has width</div>
```

We assign a `width`

```css
div {
  width: calc(30% - 20px);
}
```

We add the JavaScript

```js
const styleMap = document.querySelector("div").computedStyleMap();

console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"}
console.log(styleMap.get("width").operator); // 'sum'
console.log(styleMap.get("width").values); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2}
console.log(styleMap.get("width").values[0]); // CSSUnitValue {value: 30, unit: "percent"}
console.log(styleMap.get("width").values[0].value); // 30
console.log(styleMap.get("width").values[0].unit); // 'percent'
console.log(styleMap.get("width").values[1]); // CSSUnitValue {value: -20, unit: "px"}
console.log(styleMap.get("width").values[1].value); // -20
console.log(styleMap.get("width").values[1].unit); // 'px'
```

The specification is still evolving. In the future we may write the last three lines as:

```js
console.log(styleMap.get("width").values[1]); // CSSMathNegate {value: CSSUnitValue, operator: "negate"}
console.log(styleMap.get("width").values[1].value); // CSSUnitValue {value: 20, unit: "px"}
console.log(styleMap.get("width").values[1].value.unit); // 'px'
```

Specifications
--------------

| Specification |
| --- |
| CSS Typed OM Level 1 # cssmathsum |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


HTMLLinkElement - Web APIs

HTMLLinkElement
===============

The **`HTMLLinkElement`** interface represents reference information for external resources and the relationship of those resources to a document and vice versa (corresponds to `<link>` element; not to be confused with `<a>`, which is represented by `HTMLAnchorElement`). This object inherits all of the properties and methods of the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLLinkElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLLinkElement.as`

A string representing the type of content being loaded by the HTML link when `rel="preload"` or `rel="modulepreload"`.

`HTMLLinkElement.crossOrigin`

A string that corresponds to the CORS setting for this link element. See CORS settings attributes for details.

`HTMLLinkElement.disabled`

A boolean value which represents whether the link is disabled; currently only used with style sheet links.

`HTMLLinkElement.fetchPriority`

An optional string representing a hint given to the browser on how it should prioritize fetching of a preload relative to other resources of the same type. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a higher priority, `low` to fetch at a lower priority, or `auto` to indicate no preference (which is the default).

`HTMLLinkElement.href`

A string representing the URI for the target resource.

`HTMLLinkElement.hreflang`

A string representing the language code for the linked resource.

`HTMLLinkElement.media`

A string representing a list of one or more media formats to which the resource applies.

`HTMLLinkElement.referrerPolicy`

A string that reflects the `referrerpolicy` HTML attribute indicating which referrer to use.

`HTMLLinkElement.rel`

A string representing the forward relationship of the linked resource from the document to the resource.

`HTMLLinkElement.relList` Read only

A `DOMTokenList` that reflects the `rel` HTML attribute, as a list of tokens.

`HTMLLinkElement.sizes` Read only

A `DOMTokenList` that reflects the `sizes` HTML attribute, as a list of tokens.

`HTMLLinkElement.sheet` Read only

Returns the `StyleSheet` object associated with the given element, or `null` if there is none.

`HTMLLinkElement.type`

A string representing the MIME type of the linked resource.

### Obsolete properties

`HTMLLinkElement.charset`
Deprecated

A string representing the character encoding for the target resource.

`HTMLLinkElement.rev`
Deprecated

A string representing the reverse relationship of the linked resource from the resource to the document.

**Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.

`HTMLLinkElement.target`
Deprecated

A string representing the name of the target frame to which the resource applies.

Instance methods
----------------

*No specific method; inherits methods from its parent, `HTMLElement`.*

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmllinkelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML element implementing this interface: `<link>`.


Navigation - Web APIs

Navigation
==========

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`Navigation`** interface of the Navigation API allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen.

It is accessed via the `Window.navigation` property.

The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded `<iframe>`s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older History API.

EventTarget

NavigationInstance properties
-------------------

*Inherits properties from its parent, `EventTarget`.*

`canGoBack` Read only
Experimental

 Returns `true` if it is possible to navigate backwards in the navigation history
 (i.e. the `currentEntry` is not the first one in the history entry list),
 and `false` if it is not.

`canGoForward` Read only
Experimental

 Returns `true` if it is possible to navigate forwards in the navigation history
 (i.e. the `currentEntry` is not the last one in the history entry list),
 and `false` if it is not.

`currentEntry` Read only
Experimental

 Returns a `NavigationHistoryEntry` object representing the location the user is currently
 navigated to right now.

`transition` Read only
Experimental

 Returns a `NavigationTransition` object representing the status of an in-progress navigation,
 which can be used to track it. Returns `null` if no navigation is currently in progress.

Instance methods
----------------

*Inherits methods from its parent, `EventTarget`.*

`back()`
Experimental

Navigates backwards by one entry in the navigation history.

`entries()`
Experimental

Returns an array of `NavigationHistoryEntry` objects representing all existing history entries.

`forward()`
Experimental

Navigates forwards by one entry in the navigation history.

`navigate()`
Experimental

Navigates to a specific URL, updating any provided state in the history entries list.

`reload()`
Experimental

Reloads the current URL, updating any provided state in the history entries list.

`traverseTo()`
Experimental

Navigates to a specific `NavigationHistoryEntry` identified by `key`.

`updateCurrentEntry()`
Experimental

 Updates the state of the `currentEntry`; used
 in cases where the state change will be independent from a navigation or reload.

Events
------

`currententrychange`
Experimental

Fired when the `Navigation.currentEntry` has changed.

`navigate`
Experimental

Fired when any type of navigation is initiated, allowing you to intercept as required.

`navigateerror`
Experimental

Fired when a navigation fails.

`navigatesuccess`
Experimental

Fired when a successful navigation has finished.

Examples
--------

### Moving forwards and backwards in the history

```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

### Traversing to a specific history entry

```js
// On JS startup, get the key of the first loaded page
// so the user can always go back there.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => navigation.traverseTo(key);

// Navigate away, but the button will always work.
await navigation.navigate("/another\_url").finished;
```

### Navigating and updating state

```js
navigation.navigate(url, { state: newState });
```

Or

```js
navigation.reload({ state: newState });
```

Or if the state is independent from a navigation or reload:

```js
navigation.updateCurrentEntry({ state: newState });
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # navigation-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


WebGLRenderbuffer - Web APIs

WebGLRenderbuffer
=================

The **WebGLRenderbuffer** interface is part of the WebGL API and represents a buffer that can contain an image, or that can be a source or target of a rendering operation.

WebGLObject

WebGLRenderbufferDescription
-----------

The `WebGLRenderbuffer` object does not define any methods or properties of its own and its content is not directly accessible. When working with `WebGLRenderbuffer` objects, the following methods of the `WebGLRenderingContext` are useful:

* `WebGLRenderingContext.bindRenderbuffer()`
* `WebGLRenderingContext.createRenderbuffer()`
* `WebGLRenderingContext.deleteRenderbuffer()`
* `WebGLRenderingContext.isRenderbuffer()`
Examples
--------

### Creating a render buffer

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
const buffer = gl.createRenderbuffer();
```

Specifications
--------------

| Specification |
| --- |
| WebGL Specification # 5.7 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebGLRenderingContext.bindRenderbuffer()`
* `WebGLRenderingContext.createRenderbuffer()`
* `WebGLRenderingContext.deleteRenderbuffer()`
* `WebGLRenderingContext.isRenderbuffer()`
* Other buffers: `WebGLBuffer`, `WebGLFramebuffer`


NotificationEvent - Web APIs

NotificationEvent
=================

The **`NotificationEvent`** interface of the Notifications API represents a notification event dispatched on the `ServiceWorkerGlobalScope` of a `ServiceWorker`.

This interface inherits from the `ExtendableEvent` interface.

>
> **Note**: Only persistent notification events, fired at the `ServiceWorkerGlobalScope` object, implement the `NotificationEvent` interface. Non-persistent notification events, fired at the `Notification` object, implement the `Event` interface.
>
>
>

Event

ExtendableEvent

NotificationEventConstructor
-----------

`NotificationEvent()`

Creates a new `NotificationEvent` object.

Instance properties
-------------------

*Also inherits properties from its parent interface, `ExtendableEvent`*.

`NotificationEvent.notification` Read only

Returns a `Notification` object representing the notification that was clicked to fire the event.

`NotificationEvent.action` Read only

Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button.

Instance methods
----------------

*Also inherits methods from its parent interface, `ExtendableEvent`*.

Example
-------

```js
self.addEventListener("notificationclick", (event) => {
  console.log(`On notification click: ${event.notification.tag}`);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});
```

Specifications
--------------

| Specification |
| --- |
| Notifications API Standard # notificationevent |

**Note:** This interface is specified in the Notifications API, but accessed through `ServiceWorkerGlobalScope`.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMError - Web APIs

DOMError
========

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`DOMError`** interface describes an error object that contains an error name.

Instance properties
-------------------

`DOMError.name` Read only
Deprecated

Returns a string representing one of the error type names (see below).

`DOMError.message` Read only
Deprecated

Returns a string representing a message or description associated with the given error type name.

Error types
-----------

| Type | Description |
| --- | --- |
| `IndexSizeError` | The index is not in the allowed range (e.g. thrown in a `range` object). |
| `HierarchyRequestError` | The node tree hierarchy is not correct. |
| `WrongDocumentError` | The object is in the wrong `document`. |
| `InvalidCharacterError` | The string contains invalid characters. |
| `NoModificationAllowedError` | The object can not be modified. |
| `NotFoundError` | The object can not be found here. |
| `NotSupportedError` | The operation is not supported |
| `InvalidStateError` | The object is in an invalid state. |
| `SyntaxError` | The string did not match the expected pattern. |
| `InvalidModificationError` | The object can not be modified in this way. |
| `NamespaceError` | The operation is not allowed by Namespaces in XML |
| `InvalidAccessError` | The object does not support the operation or argument. |
| `TypeMismatchError` | The type of the object does not match the expected type. |
| `SecurityError` | The operation is insecure. |
| `NetworkError` | A network error occurred. |
| `AbortError` | The operation was aborted. |
| `URLMismatchError` | The given URL does not match another URL. |
| `QuotaExceededError` | The quota has been exceeded. |
| `TimeoutError` | The operation timed out. |
| `InvalidNodeTypeError` | The node is incorrect or has an incorrect ancestor for this operation. |
| `DataCloneError` | The object can not be cloned. |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `DOMException`


MIDIPort - Web APIs

MIDIPort
========

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`MIDIPort`** interface of the Web MIDI API represents a MIDI input or output port.

A `MIDIPort` instance is created when a new MIDI device is connected. Therefore it has no constructor.

EventTarget

MIDIPortInstance properties
-------------------

`MIDIPort.id` Read only

Returns a string containing the unique ID of the port.

`MIDIPort.manufacturer` Read only

Returns a string containing the manufacturer of the port.

`MIDIPort.name` Read only

Returns a string containing the system name of the port.

`MIDIPort.type` Read only

Returns a string containing the type of the port, one of:

`"input"`

The `MIDIPort` is an input port.

`"output"`

The `MIDIPort` is an output port.

`MIDIPort.version` Read only

Returns a string containing the version of the port.

`MIDIPort.state` Read only

Returns a string containing the state of the port, one of:

`"disconnected"`

The device that this `MIDIPort` represents is disconnected from the system.

`"connected"`

The device that this `MIDIPort` represents is currently connected.

`MIDIPort.connection` Read only

Returns a string containing the connection state of the port, one of:

`"open"`

The device that this `MIDIPort` represents has been opened and is available.

`"closed"`

The device that this `MIDIPort` represents has not been opened, or has been closed.

`"pending"`

The device that this `MIDIPort` represents has been opened but has subsequently disconnected .

Instance methods
----------------

*This interface also inherits methods from `EventTarget`.*

`MIDIPort.open()`

Makes the MIDI device connected to this `MIDIPort` explicitly available, and returns a `Promise` which resolves once access to the port has been successful.

`MIDIPort.close()`

Makes the MIDI device connected to this `MIDIPort` unavailable, changing the `state` from `"open"` to `"closed"`. This returns a `Promise` which resolves once the port has been closed.

Events
------

`MIDIPort.statechange_event`

Called when an existing port changes its state or connection.

Examples
--------

### List ports and their information

The following example lists input and output ports, and displays information about them using properties of `MIDIPort`.

```js
function listInputsAndOutputs(midiAccess) {
  for (const entry of midiAccess.inputs) {
    const input = entry[1];
    console.log(
      `Input port [type:'${input.type}'] id:'${input.id}' manufacturer: '${input.manufacturer}' name: '${input.name}' version: '${input.version}'`,
    );
  }

  for (const entry of midiAccess.outputs) {
    const output = entry[1];
    console.log(
      `Output port [type:'${output.type}'] id: '${output.id}' manufacturer: '${output.manufacturer}' name: '${output.name}' version: '${output.version}'`,
    );
  }
}
```

### Add available ports to a select list

The following example takes the list of input ports and adds them to a select list, in order that a user can choose the device they want to use.

```js
inputs.forEach((port, key) => {
  const opt = document.createElement("option");
  opt.text = port.name;
  document.getElementById("inputportselector").add(opt);
});
```

Specifications
--------------

| Specification |
| --- |
| Web MIDI API # MIDIPort |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Audio Output Devices API - Web APIs

Audio Output Devices API
========================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **Audio Output Devices API** allows web applications to prompt users about what output device should be used for audio playback.

Concepts and usage
------------------

 Operating systems commonly allow users to specify that audio should be played from speakers, a Bluetooth headset, or some other audio output device.
 This API allows applications to provide this same functionality from within a web page.

Even if allowed by a permission policy, access to a particular audio output device still requires explicit user permission, as the user may be in a location where playing audio through some output devices is not appropriate.

 The API provides the `MediaDevices.selectAudioOutput()` method that allows users to select their desired audio output from those that are allowed by the `speaker-selection` directive of the `Permissions-Policy` HTTP header for the document.
 The selected device then has user permission, allowing it to be enumerated with `MediaDevices.enumerateDevices()` and set as the audio output device using `HTMLMediaElement.setSinkId()`.

 Audio devices may arbitrarily connect and disconnect.
 Applications that wish to react to this kind of change can listen to the `devicechange` event and use `enumerateDevices()` to determine if `sinkId` is present in the returned devices.
 This might trigger, for example, pausing or unpausing playback.

Interfaces
----------

### Extensions to interfaces

The Audio Output Devices API extends the following APIs, adding the listed features:

#### MediaDevices

`MediaDevices.selectAudioOutput()`

 This method prompts the user to select a specific audio output device, for example a speaker or headset.
 Selecting a device grants user permission to use that device and returns information about the device, including its ID.

#### HTMLMediaElement

`HTMLMediaElement.setSinkId()`

This method sets the ID of the audio device to use for output, which will be used if permitted.

`HTMLMediaElement.sinkId`

This property returns the unique ID of the audio device being used for output, or an empty string if the default user agent device is being used.

Security requirements
---------------------

Access to the API is subject to the following constraints:

* All methods and properties may only be called in a secure context.
* `MediaDevices.selectAudioOutput()` grants user permission for a selected device to be used as the audio output sink:
    + Access may be gated by the `speaker-selection` HTTP Permission Policy.
    + Transient user activation is required.
     The user has to interact with the page or a UI element for the method to be called.
* `HTMLMediaElement.setSinkId()` sets a permitted ID as the audio output:
    + Access may be gated by the `speaker-selection` HTTP Permission Policy.
    + User permission is required to set a non-default device ID.
        - This can come from selection in the prompt launched by `MediaDevices.selectAudioOutput()`
        - User permission to set the output device is also implicitly granted if the user has already granted permission to use a media input device in the same group with `MediaDevices.getUserMedia()`.

Examples
--------

Here's an example of using `selectAudioOutput()`, within a function that is triggered by a button click, and then setting the selected device as the audio output.

 The code first checks if `selectAudioOutput()` is supported, and if it is, uses it to select an output and return a device ID.
 We then play some audio using the default output, and then call `setSinkId()` in order to switch to the selected output device.

```js
document.querySelector("#myButton").addEventListener("click", async () => {
  if (!navigator.mediaDevices.selectAudioOutput) {
    console.log("selectAudioOutput() not supported or not in secure context.");
    return;
  }

  // Display prompt to select device
  const audioDevice = await navigator.mediaDevices.selectAudioOutput();

  // Create an audio element and start playing audio on the default device
  const audio = document.createElement("audio");
  audio.src = "https://example.com/audio.mp3";
  audio.play();

  // Change the sink to the selected audio output device.
  audio.setSinkId(audioDevice.deviceId);
});
```

Note that if you log the output details, they might look something like this:

```js
console.log(
  `${audioDevice.kind}: ${audioDevice.label} id = ${audioDevice.deviceId}`,
);
// audiooutput: Realtek Digital Output (Realtek(R) Audio) id = 0wE6fURSZ20H0N2NbxqgowQJLWbwo+5ablCVVJwRM3k=
```

Specifications
--------------

| Specification |
| --- |
| Audio Output Devices API  |

Browser compatibility
---------------------

### api.MediaDevices.selectAudioOutput

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.HTMLMediaElement.setSinkId

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.HTMLMediaElement.sinkId

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### http.headers.Permissions-Policy.speaker-selection

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGAnimatedString - Web APIs

SVGAnimatedString
=================

The **`SVGAnimatedString`** interface represents string attributes which can be animated from each SVG declaration. You need to create SVG attribute before doing anything else, everything should be declared inside this.

Instance properties
-------------------

`SVGAnimatedString.animVal` Read only

This is a string representing the animation value. If the given attribute or property is being animated it contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, it contains the same value as baseVal.

`SVGAnimatedString.baseVal`

This is a string representing the base value. The base value of the given attribute before applying any animations. Setter throws DOMException.

Instance methods
----------------

*The `SVGAnimatedString` interface do not provide any specific methods.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGAnimatedString |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PerformanceLongTaskTiming - Web APIs

PerformanceLongTaskTiming
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`PerformanceLongTaskTiming`** interface provides information about tasks that occupy the UI thread for 50 milliseconds or more.

Description
-----------

Long tasks that block the main thread for 50ms or more cause, among other issues:

* Delayed Time to interactive (TTI).
* High/variable input latency.
* High/variable event handling latency.
* Janky animations and scrolling.

A long task is any uninterrupted period where the main UI thread is busy for 50ms or longer. Common examples include:

* Long-running event handlers.
* Expensive reflows and other re-renders.
* Work the browser does between different turns of the event loop that exceeds 50 ms.

Long tasks refer to "culprit browsing context container", or "the container" for short, which is the top-level page, `<iframe>`, `<embed>` or `<object>` that the task occurred within.

For tasks that don't occur within the top-level page and for figuring out which container is responsible for the long task, the `TaskAttributionTiming` interface provides the `containerId`, `containerName` and `containerSrc` properties, which may provide more information about the source of the task.

Inheritance
-----------

`PerformanceLongTaskTiming` inherits from `PerformanceEntry`.

PerformanceEntry

PerformanceLongTaskTimingInstance properties
-------------------

This interface extends the following `PerformanceEntry` properties for long task timing performance entry types by qualifying them as follows:

`PerformanceEntry.duration` Read only
Experimental

Returns a `DOMHighResTimeStamp` representing the elapsed time between the start and end of the task, with a 1ms granularity.

`PerformanceEntry.entryType` Read only
Experimental

Always returns `"longtask"`

`PerformanceEntry.name` Read only
Experimental

Returns one of the following strings referring to the browsing context or frame that can be attributed to the long task:

* `"cross-origin-ancestor"`
* `"cross-origin-descendant"`
* `"cross-origin-unreachable"`
* `"multiple-contexts"`
* `"same-origin-ancestor"`
* `"same-origin-descendant"`
* `"same-origin"`
* `"self"`
* `"unknown"`

`PerformanceEntry.startTime` Read only
Experimental

Returns a `DOMHighResTimeStamp` representing the time when the task started.

This interface also supports the following properties:

`PerformanceLongTaskTiming.attribution` Read only
Experimental

Returns a sequence of `TaskAttributionTiming` instances.

Instance methods
----------------

`PerformanceLongTaskTiming.toJSON()`
Experimental

Returns a JSON representation of the `PerformanceLongTaskTiming` object.

Examples
--------

### Getting long tasks

To get long task timing information, create a `PerformanceObserver` instance and then call its `observe()` method, passing in `"longtask"` as the value of the `type` option. You also need to set `buffered` to `true` to get access to long tasks the user agent buffered while constructing the document. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceLongTaskTiming` objects which you can analyze.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});

observer.observe({ type: "longtask", buffered: true });
```

Specifications
--------------

| Specification |
| --- |
| Long Tasks API # sec-PerformanceLongTaskTiming |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `TaskAttributionTiming`


SVGRenderingIntent - Web APIs

SVGRenderingIntent
==================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`SVGRenderingIntent`** interface defines the enumerated list of possible values for `rendering-intent` attributes or descriptors.

**Warning:** This interface was removed in the SVG 2 specification.

Constants
---------

| Name | Value | Description |
| --- | --- | --- |
| `RENDERING_INTENT_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `RENDERING_INTENT_AUTO` | 1 | Corresponds to the value `auto`. |
| `RENDERING_INTENT_PERCEPTUAL` | 2 | Corresponds to the value `perceptual`. |
| `RENDERING_INTENT_RELATIVE_COLORIMETRIC` | 3 | Corresponds to the value `relative-colorimetric`. |
| `RENDERING_INTENT_SATURATION` | 4 | Corresponds to the value `saturation`. |
| `RENDERING_INTENT_ABSOLUTE_COLORIMETRIC` | 5 | Corresponds to the value `absolute-colorimetric`. |

Instance properties
-------------------

*This interface doesn't implement any specific properties.*

Instance methods
----------------

*This interface doesn't implement any specific methods.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGRenderingIntent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `rendering-intent`


Server-sent events - Web APIs

Server-sent events
==================

Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as *Events + data* inside the web page.

**Note:** This feature is available in Web Workers

**Note:** Firefox does not currently support the use of server-sent events in service workers (it does support them in dedicated and shared workers). See Firefox bug 1681218.

Concepts and usage
------------------

To learn how to use server-sent events, see our article Using server-sent events.

Interfaces
----------

`EventSource`

Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.

Examples
--------

* Simple SSE demo using PHP
Specifications
--------------

| Specification |
| --- |
| HTML Standard # server-sent-events |

See also
--------

### Tools

* Mercure: a real-time communication protocol (publish-subscribe) built on top of SSE
* EventSource polyfill for Node.js
* Remy Sharp's EventSource polyfill
* Yaffle's EventSource polyfill
* Rick Waldron's jquery plugin
* intercooler.js declarative SSE support
### Related Topics

* Fetching data from the server
* JavaScript
* WebSockets
### Other resources

* A Twitter like application powered by server-sent events and its code on GitHub.


LockManager - Web APIs

LockManager
===========

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`LockManager`** interface of the Web Locks API provides methods for requesting a new `Lock` object and querying for an existing `Lock` object. To get an instance of `LockManager`, call `navigator.locks`.

**Note:** This feature is available in Web Workers

Instance methods
----------------

`LockManager.request()`

Requests a `Lock` object with parameters specifying its name and characteristics.

`LockManager.query()`

Returns a `Promise` that resolves with an object that contains information about held and pending locks.

Specifications
--------------

| Specification |
| --- |
| Web Locks API # api-lock-manager |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGFEGaussianBlurElement - Web APIs

SVGFEGaussianBlurElement
========================

The **`SVGFEGaussianBlurElement`** interface corresponds to the `<feGaussianBlur>` element.

EventTarget

Node

Element

SVGElement

SVGFEGaussianBlurElementInstance properties
-------------------

*This interface also inherits properties from its parent interface, `SVGElement`.*

`SVGFEGaussianBlurElement.edgeMode` Read only

An `SVGAnimatedEnumeration` corresponding to the `edgeMode` attribute of the given element. Returns two identical values that are one of the following values:

`SVG_EDGEMODE_UNKNOWN` (0)

The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.

`SVG_EDGEMODE_DUPLICATE` (1)

Corresponds to the `duplicate` value.

`SVG_EDGEMODE_WRAP` (2)

Corresponds to the `wrap` value.

`SVG_EDGEMODE_NONE` (3)

Corresponds to `none` value.

`SVGFEGaussianBlurElement.height` Read only

An `SVGAnimatedLength` corresponding to the `height` attribute of the given element.

`SVGFEGaussianBlurElement.in1` Read only

An `SVGAnimatedString` corresponding to the `in` attribute of the given element.

`SVGFEGaussianBlurElement.result` Read only

An `SVGAnimatedString` corresponding to the `result` attribute of the given element.

`SVGFEGaussianBlurElement.stdDeviationX` Read only

An `SVGAnimatedNumber` corresponding to the (possibly automatically computed) X component of the `stdDeviation` attribute of the given element.

`SVGFEGaussianBlurElement.stdDeviationY` Read only

An `SVGAnimatedNumber` corresponding to the (possibly automatically computed) Y component of the `stdDeviation` attribute of the given element.

`SVGFEGaussianBlurElement.width` Read only

An `SVGAnimatedLength` corresponding to the `width` attribute of the given element.

`SVGFEGaussianBlurElement.x` Read only

An `SVGAnimatedLength` corresponding to the `x` attribute of the given element.

`SVGFEGaussianBlurElement.y` Read only

An `SVGAnimatedLength` corresponding to the `y` attribute of the given element.

Instance methods
----------------

*This interface also inherits methods of its parent, `SVGElement`.*

`SVGFEGaussianBlurElement.setStdDeviation()`

Sets the values for the `stdDeviation` attribute.

Specifications
--------------

| Specification |
| --- |
| Filter Effects Module Level 1 # InterfaceSVGFEGaussianBlurElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<feGaussianBlur>`


CSSFontFaceRule - Web APIs

CSSFontFaceRule
===============

The **`CSSFontFaceRule`** interface represents an `@font-face` at-rule.

CSSRule

CSSFontFaceRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSFontFaceRule.style` Read only

Returns a `CSSStyleDeclaration`.

Instance methods
----------------

*Inherits methods from its ancestor `CSSRule`.*

Examples
--------

This example uses the CSS found as an example on the `@font-face` page. The first `CSSRule` returned will be a `CSSFontFaceRule`.

```css
@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"),
    url(MgOpenModernaBold.ttf);
  font-weight: bold;
}
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); //a CSSFontFaceRule
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # om-fontface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


AudioSinkInfo - Web APIs

AudioSinkInfo
=============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`AudioSinkInfo`** interface of the Web Audio API represents information describing an `AudioContext`'s sink ID, retrieved via `AudioContext.sinkId`.

Instance properties
-------------------

`type` Read only
Experimental

Returns the type of the audio output device.

Examples
--------

If a new `AudioContext` is created with a `sinkId` value of `{ type: 'none' }`, calling `AudioContext.sinkId` later in the code will return a `AudioSinkInfo` object containing `type: 'none'`. This is currently the only value available.

```js
audioCtx = new window.AudioContext({
  sinkId: { type: "none" },
});

// ...

audioCtx.sinkId;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # AudioSinkInfo |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* SetSinkId test example
* `AudioContext.setSinkId()`
* `AudioContext.sinkId`
* `sinkchange`