Skip to content

Std.Clock

effect Clock

The current point in time, and waiting.

  • suspend fn sleep(ms: Int) -> ()

    Waits ms milliseconds. A negative ms is the same as 0.

  • fn now() -> Instant

    The current point in time.

handler SystemClock: Clock
uses { Async }

The host’s clock. sleep waits for a timer (JS setTimeout, C the runtime’s event loop). SystemClock depends on Async ([effect.async]), and interrupting the sleeping fiber clears the timer. now is milliseconds since the Unix epoch (JS Date.now()).

handler TestClock: Clock
uses { Async, State[Instant] }

The test handler. The current time is State[Instant], so use it inside State.run with the starting time:

start = Instant.from_unix_milliseconds(Int64.from_int(0))
(_, end) = State.run(start, || with TestClock {
clock <- Clock
clock.sleep(1000)
})

The time is virtual ([effect.state]). sleep really waits: when no fiber can go on and the host has nothing pending, the time moves forward to the earliest time a sleeper waits for, and that sleeper wakes (sleepers with the same time wake in the order they called sleep). With one fiber this is the same as moving the time forward by ms at once. A negative ms is the same as 0. now returns the time in State[Instant]. TestClock depends on Async.