GUIDE / BUILDING APPLICATIONS

Timers

Repeat work with interval, delay it with timeout, debounce input, pause a timer while nobody sees it, and know when timers stop.

Core janelkit Included with janelkit. Nothing extra to install.
CHAPTER 20 / 29~4 min read · try examples at your own pace
Alpha / 0.2 — These pages document JanelKit 0.2 and its packages. Each series (0.1, 0.2…) may change the public API, always with migration notes: see Changes and migration. The website uses Svelte; the desktop examples use Python and JanelKit, not JavaScript.

What you will learn

  • How interval repeats a function and timeout runs one later.
  • How to stop, restart and change a timer.
  • How to debounce typing with timeout.restart.
  • How when= and is_visible() pause a timer while its component is not seen.
  • When timers stop on their own and when you must stop them.

interval: repeat every few milliseconds

interval(ms, fn), or @interval(ms) as a decorator, calls fn every ms milliseconds and returns a Timer. It starts as soon as it is created, so create it during setup. All the state changes of one tick are grouped, so updating fifty values in a tick redraws once.

Timer.active is reactive. stop() pauses it; start() and restart() start counting again from zero. To change the period, set timer.ms and call restart().

janel
<script lang="python">
from janelkit import state, interval

ticks = state(0)

@interval(1000)
def clock():
    ticks.value += 1
</script>

<column padding={24} gap={12}>
  <text>Ticks: {ticks}</text>
  <text>Running: {clock.active}</text>
  <row gap={8}>
    <button on:click={clock.stop()}>Stop</button>
    <button on:click={clock.restart()}>Restart</button>
  </row>
</column>
Copy

Complete component · Save as src/App.janel in a scaffolded project.

How it works

  1. @interval(1000) turns clock into a Timer that calls the function every second.
  2. clock.active is reactive, so Running follows Stop and Restart.
  3. Restart starts a fresh one-second wait, it does not reset ticks.

What you should see

Ticks goes up once per second and Running says True. Stop freezes the count and shows Running: False; Restart resumes.

timeout: do it once, later

timeout(ms, fn) calls fn once after ms milliseconds. Like interval, it starts when it is created and returns a Timer. restart() starts the wait again from zero, which is exactly what debouncing needs: wait until the user stops typing, then act once.

janel
<script lang="python">
from janelkit import state, timeout

query = state("")
searched = state("nothing yet")

def search():
    searched.value = query.value or "nothing yet"

debounce = timeout(400, search)
debounce.stop()        # do not search until the user types
</script>

<column padding={24} gap={12}>
  <textfield bind:value={query} on:input={debounce.restart()} label="Search" />
  <text>Searched for: {searched}</text>
</column>
Copy

Complete component · Save as src/App.janel in a scaffolded project.

How it works

  1. timeout starts counting at creation; stop() waits for the first keystroke instead.
  2. Every keystroke calls restart(), so the search runs 400 ms after the last one, not after each.
  3. To show a message for a few seconds, create timeout(3000, lambda: notice.set("")) after setting it.

What you should see

Typing ada quickly shows Searched for: ada shortly after the last letter, once.

Async callbacks skip, they do not pile up

A timer’s function can be async def, for example to fetch data with background. If a tick is still running when the next one is due, the next one is skipped instead of starting in parallel. An error in the function is logged with its name, and the timer keeps going.

The timer measures itself: runs counts the completed runs, skipped the ticks skipped because the previous run was still going, and last_duration is the duration in seconds of the last complete run, async part included. They are not reactive; read them to find out whether a cycle fits in its period. If skipped keeps growing, it does not.

python
# In a component script; read_processes is a blocking function of yours.
from janelkit import state, interval, background

processes = state([])

@interval(1000)
async def refresh():
    processes.value = await background(read_processes)
Copy

Count only while it matters: when=

A component that is not seen still runs its timers: inside {#hidden}, in a list row scrolled out of view, or on a page or section of janelkit-router that is not shown. To avoid work nobody sees, pass a condition: interval(ms, fn, when=condition), and the same for timeout. The condition can be a state, a computed, is_visible() or a function that reads them, such as lambda: visible.value and camera.ready.value. While it is false the timer does not count; when it becomes true again, it counts from zero. stop() wins over when=: a timer stopped by hand does not start again by itself.

is_visible() returns a computed that says whether the component is seen. It is False in a covered page, in a section that is not the current one, inside a {#hidden} that hides it and in a <list> row out of view. The root of a window is always seen; minimizing does not count. Call it in the script, like on_mount.

python
# In a component script; read_cpu is a function of yours.
from janelkit import state, interval, is_visible

cpu = state(0.0)
visible = is_visible()

@interval(250, when=visible)
def sample():
    cpu.value = read_cpu()
Copy

How it works

  1. visible is a computed, so the timer follows it without any code of yours.
  2. The same visible can drive an effect, for example to release a camera while the view is hidden.

Common mistakes

  • when= pauses the timer, not the rest of the script. An effect that saves data keeps running while hidden, which is usually what you want.

Learn moreReal-time applications ↗

When timers stop

A timer created in a component stops when the component is destroyed, also when it was created after an await in a handler or a task. A timer created in an ordinary module, outside any component, runs until you call stop(); JanelKit keeps it alive even if you do not keep a reference. Timers need the application’s event loop: they do not tick during a blocking function, and they do not tick in a plain Python script without the application running.

Common mistakes

  • Do not write a while loop with time.sleep to repeat work; it freezes the window. Use interval.
  • stop() prevents future ticks; it does not cancel an async tick that is already running.
  • A timer inside {#hidden}, in a list row out of view or on a covered page keeps running. Give it when=is_visible() if it should pause.

Learn moreLifecycle and effects ↗Async work ↗

Key points

  • interval repeats, timeout runs once; both start when created and return a Timer.
  • stop, start and restart control them; active is reactive.
  • restart on each keystroke debounces input; when= pauses a timer while its component is not seen.

English documentation based on the JanelKit source. For additional details, browse the source docs ↗.