timer
The timer module schedules callback functions to run later or repeatedly. Each scheduling call returns an integer handle that can be passed to timer.clear to cancel it. Callbacks are invoked with no arguments and run inside the same VM, so timers should only be used in long-running programs that outlive their callbacks. Import it with import timer.
Functions
| Function | Signature | Description |
|---|---|---|
setTimeout | timer.setTimeout(ms: int, fn) → int | run fn once after ms milliseconds; returns a cancellable handle |
setInterval | timer.setInterval(ms: int, fn) → int | run fn repeatedly every ms milliseconds until cleared; returns a handle |
clear | timer.clear(id: int) → bool | cancel a pending timeout or interval; false if already cleared or fired |
Note: a setInterval callback that takes longer than ms to run causes ticks to coalesce (the next tick fires right after the previous one returns), matching Go’s time.Ticker rather than browser setInterval.
Example
import timer
// fire once after one second
timer.setTimeout(1000, fn() {
print("tick")
})
// repeat every 500ms, then stop after a while
let id = timer.setInterval(500, fn() {
print("poll")
})
timer.clear(id)