Atomics waitAsync Non-Blocking Wait
Wait on shared memory without freezing the event loop: waitAsync returns a promise while timers keep firing, unlike the blocking Atomics.wait.
Code
// Atomics.wait() blocks the thread until notified; waitAsync is the
// non-blocking variant: it returns a promise so the event loop keeps
// serving timers and I/O while the wait is pending.
const cells = new Int32Array(new SharedArrayBuffer(8));
// Keep timers firing while the wait is pending; stop once the wait settles
let ticking = true;
let ticks = 0;
setTimeout(function tick() {
ticks += 1;
if (ticking) setTimeout(tick, 10);
}, 10);
// Wait up to 100ms for cell 0 to change from 0. Nobody notifies it, so this times out.
const pending = Atomics.waitAsync(cells, 0, 0, 100);
console.log("returned a promise:", pending.async);
// The promise settles with the same result string Atomics.wait would return
const outcome = await pending.value;
ticking = false;
console.log("wait outcome:", outcome);
console.log("event loop stayed live during the wait:", ticks > 0);
// When the observed value is already different, the result is available synchronously
const immediate = Atomics.waitAsync(cells, 0, 99, 1_000);
console.log("already satisfied:", !immediate.async, immediate.value);Output
Captured from a sandboxed run of this snippet in the build pipeline.
returned a promise: true
wait outcome: timed-out
event loop stayed live during the wait: true
already satisfied: true not-equalHow the file behaves
The shape of it: the function tick, doing all the work.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
Entry signature: function tick()
The run prints labeled lines — returned a promise:, wait outcome:, event loop stayed live during the wait: — when the file runs.
Key statements
const outcome = await pending.value;
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `tick` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.