Overview

onInterval and onTimeout wrap setInterval / setTimeout and clear themselves when the component unmounts — no manual clearInterval / clearTimeout.

Both must be called in the outer (setup) function. Handlers may return a per-tick cleanup that runs before the next fire and on unmount.

Timer hooks

API
Behavior
Cleanup
onInterval(fn, ms) Repeats every ms Interval cleared on unmount; optional per-tick cleanup.
onTimeout(fn, ms) Fires once after ms Cancelled on unmount if not yet fired.

onInterval — live clock

onInterval schedules a repeating callback at the given millisecond interval. The interval is automatically cleared when the component unmounts.

import { html, atom, onInterval, renderApp } from 'mates';

const Clock = () => {
const time = atom(new Date().toLocaleTimeString());

// Auto-clears interval when component unmounts
onInterval(() => {
time.set(new Date().toLocaleTimeString());
}, 1000);

return () => html`
<h1 class="mono card-title">${time()}</h1>
<p class="label">Updates every second via onInterval</p>
`;
};
renderApp(Clock, document.getElementById('app'));

onTimeout — delayed message

onTimeout fires a callback once after the given delay. If the component unmounts before the timer fires, the timeout is automatically cancelled.

import { html, atom, onTimeout, renderApp } from 'mates';

const DelayedMessage = () => {
const shown = atom(false);

// Fires once after 2 seconds, auto-cancelled if unmounted before then
onTimeout(() => { shown.set(true); }, 2000);

return () => html`
${shown()
? html`<span class="tag tag-success m-5">Message appeared after 2s!</span>`
: html`<p class="muted">Waiting 2 seconds…</p>`
}
`;
};
renderApp(DelayedMessage, document.getElementById('app'));