Timer Module

Promise-based sleep and delay helpers

Sections

Terminology & Glossary
πŸ“– Documentation
Navigation
31 sectionsv0.1
πŸ“„ Timer Module β€” glaze help timer-module
timer-module

Timer Module

Promise-based sleep and delay helpers

Topictimermodulesgojajavascriptgoja-repl

The timer module exposes a single Promise-based helper: sleep. It lets JavaScript code pause asynchronously without blocking the runtime owner goroutine.

The module requires a runtime with owner services because the backing goroutine dispatches resolution back onto the goja runtime through the owner event loop.

JavaScript usage

const timer = require("timer");

async function delayedHello() {
  await timer.sleep(500);
  console.log("hello after 500 ms");
}

delayedHello();

Module API

sleep(ms)

Returns a Promise that resolves after ms milliseconds. The timer is canceled if either the owner call context or the runtime lifetime context ends before the delay completes.

If ms is negative, the Promise rejects with an error string.

Design notes

sleep is a thin wrapper around Go's time.Timer that sends its resolve call through the runtime owner's dispatch queue. This means the JavaScript Promise resolves on the correct goroutine and does not race with concurrent runtime access.

Troubleshooting

ProblemCauseSolution
"timer module requires runtime services" panicThe runtime was built without owner-based servicesUse a factory created with engine.NewBuilder().Build() rather than a bare goja.New()
Promise never resolves after a long delayThe owner call context was canceled or timed outIncrease the context deadline on the owner call, or move the sleep to a longer-lived context
Negative duration rejectedms < 0Pass a non-negative integer for the sleep duration