Skip to main content

Sleep

std.async.sleep(ms) is the cooperative way to wait. It yields the current fiber, polls the clock on the worker pool, and resumes after ms milliseconds. While it waits, other fibers (servers, timers, spawned tasks) keep running.

print("before")
std.async.sleep(50)
print("after (50 ms later)")

Why not a busy loop?

// BAD — spins at full CPU and only yields every 64 iterations
var n = 0
while (n < 1000000) { n++ }

// GOOD — yields explicitly and wakes on time
std.async.sleep(100)

Every 64 loop statements the engine yields automatically (see Overview), so a busy loop does not deadlock — but it wastes CPU. Prefer sleep for polling and back-off:

// poll loop that sleeps between checks
while (std.file.exists("wait.txt") == false) {
std.async.sleep(200) // gentle polling, not spinning
}

Resolution and chaining

  • ms is an integer milliseconds value. Sub-millisecond sleeps still yield once.
  • Chaining sleeps adds up: sleep(100); sleep(100) waits ~200 ms.
  • Combine with std.time to measure: std.time.now() + std.time.elapsed(start) (see std.time).
var t0 = std.time.now()
std.async.sleep(100)
print(std.time.elapsed(t0)) // e.g. 100

Keeping servers alive

The most common use of sleep is to keep a script alive after starting a server/timer:

var srv = std.net.http_server()
srv.routes([{path: "/", handler: fn(req) { return "hi" }}])
srv.listen(8080)
std.async.sleep(5000) // keep serving for 5 s
srv.stop()

Without the final sleep, the script would exit immediately and the server would never receive a request. The same pattern applies to std.net.tcp_server / udp / websocket (see Network).

See also

  • Overview — yield points
  • Spawn & Await — overlap sleep with other work
  • Defer — run a function after a delay without blocking the caller