Atomics.sleep to sleep in worker threads without allocation or COOP+COEP

Currently you need to allocate a dummy SharedArrayBuffer (or if you can't turn off COOP/COEP you need to use WebAssembly.Memory) just to invoke sleepSync in a worker thread:
const sab = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }).buffer; const view = new Int32Array(sab);
Atomics.wait(view, 0, 0, ms);
This is a rather cursed way to implement sleep, a very important primitive in lots of programming languages you might want to cross-compile to wasm (and FFI into a JS worker thread to sleep)
Historically, on the Atomics.pause proposal you could add in an n value to increase the sleep time but this was then ignored by browsers and so dropped to preserve cross-compatibility. Perhaps here it'd be more useful as you can restrict it to only work outside the main thread? Syntax would be Atomics.sleep(ms).

I am also aware you can lower this to 4 bytes by getting the SAB constructor from WebAssembly.Memory, but again a cursed workaround for what should be a fairly simple primitive?

For compiling to wasm one option would be to use Introducing the WebAssembly JavaScript Promise Integration API ยท V8 so that the wasm side "blocks" (suspends) but it does an async setTimeout wait on the JS side

1 Like

Yes JSPI is fine if the toolchain you're using to target wasm supports that but that requires the bundler to cooperate