The Bnlang Event Loop

The event loop in Bnlang is the core mechanism that makes asynchronous programming possible.
It allows tasks like I/O, timers, and events to run without blocking the main thread.
The event loop continuously checks for pending tasks and executes them in phases, ensuring programs remain responsive.


How the Event Loop Works

  1. Tasks are placed into queues (macrotasks, microtasks).
  2. The event loop checks the call stack. If empty, it processes the next task.
  3. Timers, I/O callbacks, and event handlers are executed.
  4. Microtasks (like promise callbacks) are always executed before the next macrotask.
  5. This cycle continues indefinitely.

Example with Timers and Promises

console.log("Start");

setTimeout(() => console.log("Timeout"), 0);

Promise.resolve().then(() => console.log("Promise"));

console.log("End");

// Output:
// Start
// End
// Promise
// Timeout

Phases of the Event Loop

The event loop is divided into phases:

  • Timers Phase → Executes callbacks from setTimeout and setInterval.
  • I/O Callbacks Phase → Executes deferred I/O callbacks.
  • Check Phase → Executes setImmediate callbacks.
  • Close Callbacks Phase → Executes close events like socket close.
    Between each phase, microtasks (like promises) are executed before moving on.

Best Practices

  • Do not block the event loop with heavy computations.
  • Use promises and async/await for clarity.
  • Break large tasks into smaller microtasks.
  • Keep the event loop free for handling I/O efficiently.