Back to Hub
THREAD MANAGEMENT • MAY 2026

Defeating the Event Loop with Atomics.wait().

A fundamental rule of JavaScript is that you cannot synchronously pause execution. If you write a while(true) loop to wait for a condition, you will burn 100% of a CPU core and crash the browser. Developers usually rely on asynchronous Promises, but when dealing with high-performance WebAssembly modules and multi-threaded compilation, asynchronous code introduces unpredictable Event Loop latency.

NitroIDE requires deterministic, synchronous execution for cross-thread mutex locking. We achieve this by bypassing the Event Loop entirely using SharedArrayBuffer and the Atomics API.

The Atomics.wait() Mechanism

When our background compiler thread needs to wait for the main thread to release a file lock, it doesn't use a Promise. It uses Atomics.wait(). This low-level C-style instruction physically puts the Web Worker thread to sleep at the OS level. It yields the CPU core completely, consuming zero processing power until it is explicitly woken up.

// Inside the Web Worker: Synchronously sleeping the thread
const lockBuffer = new Int32Array(sharedArrayBuffer);
const LOCK_INDEX = 0;

// If the value at LOCK_INDEX is 1 (locked), sleep the thread
Atomics.wait(lockBuffer, LOCK_INDEX, 1);

// --- THREAD IS COMPLETELY FROZEN HERE ---

// Execution only resumes once the main thread unlocks it
console.log('Lock released! Resuming compilation...');

Main Thread Protection: The browser engine strictly prohibits calling Atomics.wait() on the main UI thread. If it were allowed, you could permanently freeze the entire browser tab. It is an exclusive superpower reserved solely for background Web Workers.

Waking the Threads

When the main thread finishes its task (like writing a file to IndexedDB), it simply changes the value in the SharedArrayBuffer and calls Atomics.notify(). The OS instantly wakes up the sleeping Web Worker, and execution resumes on the very next line of code without waiting for the next tick of the Event Loop.

Unleash Multi-Threading.

Run heavy compilation tasks in our editor without dropping a single frame.

Launch IDE