Timers

Inside a component script, setTimeout, setInterval, clearTimeout and clearInterval are bound to the element. Any timer still pending when the element is removed is cleared.

setTimeout(callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]): number
setInterval(callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]): number
clearTimeout(id?: number): void
clearInterval(id?: number): void
const clock = useState({ now: new Date() });
setInterval(() => (clock.now = new Date()), 1000);

Behaviour

Topic Detail
Signature The same as window.setTimeout / window.setInterval, returning the same numeric ids
Cleanup Pending timeouts and all intervals are cleared when the element's signal aborts
Clearing clearTimeout and clearInterval both work for either kind of id
Window timers window.setTimeout(…) is still available and is not cleared automatically

These versions apply only inside the component script and its handlers. Modules imported by the script use the normal globals.

Example

Previewindex.htmllive-clock.html

The time is .

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Timers demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
  <script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
  <import-element from="./live-clock.html"></import-element>

  <live-clock></live-clock>
</body>
</html>
<custom-element name="live-clock">
  <script>
    const clock = useState({ time: new Date().toLocaleTimeString() });

    setInterval(() => {
      clock.time = new Date().toLocaleTimeString();
    }, 1000);
  </script>

  <p>The time is <time><slot name="#clock.time"></slot></time>.</p>
</custom-element>

Edit this page on GitHub · View as Markdown