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
- Tasks are placed into queues (macrotasks, microtasks).
- The event loop checks the call stack. If empty, it processes the next task.
- Timers, I/O callbacks, and event handlers are executed.
- Microtasks (like promise callbacks) are always executed before the next macrotask.
- 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
andsetInterval
. - 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.