Event Loop

حلقة الأحداث (Event Loop)

Advancedprogramming1 min read
js event loopcall stacktask queuemicrotaskmacrotaskjavascript runtime

Definition

The JavaScript runtime mechanism that handles asynchronous code execution, making single-threaded JS non-blocking.

آلية تشغيل JavaScript التي تتعامل مع تنفيذ الكود غير المتزامن، مما يجعل JS أحادية الخيط غير محجوبة.

Why It Matters

Understanding the event loop explains why `console.log` after `await fetch()` sees the result — and why synchronous loops can freeze the UI if they run too long.

فهم حلقة الأحداث يُفسّر لماذا `console.log` بعد `await fetch()` يرى النتيجة — ولماذا الحلقات التزامنية يمكن أن تجمّد واجهة المستخدم إذا استمرت طويلًا.

Full Definition

JavaScript is single-threaded but can handle async operations via the event loop. The call stack executes synchronous code. Async operations (fetch, setTimeout) are handled by browser Web APIs. When they complete, callbacks are placed in the task queue (macrotasks) or microtask queue (Promises). The event loop moves them to the call stack when it's empty. This is why `await` doesn't block the browser.
JavaScript أحادية الخيط لكن يمكنها معالجة العمليات غير المتزامنة عبر حلقة الأحداث. مكدس الاستدعاء ينفّذ الكود التزامني. العمليات غير المتزامنة تُعالجها Web APIs. عند اكتمالها، تُوضع الاستدعاءات في طابور المهام أو طابور المهام الصغيرة.

Example Usage

console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4'); // Output: 1, 4, 3, 2

console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4'); // المخرج: 1، 4، 3، 2

Knowledge Graph

Avoid these mistakes when using Event Loop:

1

Assuming setTimeout(() => {}, 0) runs immediately — it waits for the call stack to clear

2

Blocking the event loop with synchronous heavy computation

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using Event Loop.

Explain:
1. What is Event Loop and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Assuming setTimeout(() => {}, 0) runs immediately — it waits for the call stack to clear, Blocking the event loop with synchronous heavy computation
5. Best practices and production tips

Official Resources