Bird
Raised Fist0
Javascriptprogramming~10 mins

Event loop overview in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Event loop overview
Start: JS code runs
↓
Call stack executes sync code
↓
Async task encountered?
↓
Send async task to Web APIs
↓
Async task completes
↓
Callback added to task queue
↓
Event loop checks call stack
↓
If call stack empty, move callback to call stack
↓
Callback executes
↓
Repeat until all tasks done
JavaScript runs code on a call stack, sends async tasks to Web APIs, and uses the event loop to move callbacks back to the stack when ready.
Execution Sample
Javascript
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
console.log('End');
This code logs 'Start', schedules a timeout callback, then logs 'End'. The timeout callback runs after the sync code.
Execution Table
StepCall StackWeb APIsTask QueueEvent Loop ActionOutput
1console.log('Start')Execute sync codeStart
2console.log('Start') done, removed from stack
3setTimeout(callback, 0)Timer startedSchedule async task
4Timer counting down
5console.log('End')Execute sync codeEnd
6console.log('End') done, removed from stack
7Timer doneCallback readyEvent loop checks stack empty
8callback()Move callback to call stack
9console.log('Timeout')Execute callbackTimeout
10callback done, removed from stack
11All tasks done, program ends
💡 All synchronous code executed and all callbacks processed from the task queue.
Variable Tracker
VariableStartAfter Step 3After Step 7Final
Call StackEmptysetTimeout(callback, 0)callback()Empty
Web APIsEmptyTimer startedTimer doneEmpty
Task QueueEmptyEmptyCallback readyEmpty
OutputStartEndTimeout
Key Moments - 2 Insights
Why does 'Timeout' print after 'End' even though setTimeout delay is 0?
Because setTimeout callback goes to the task queue and waits until the call stack is empty (see steps 5-9 in execution_table).
What happens if the call stack is not empty when the async task finishes?
The event loop waits and does not move the callback to the call stack until it becomes empty (see step 7 and 8).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is on the call stack at step 3?
Aconsole.log('Start')
BsetTimeout(callback, 0)
Ccallback()
Dconsole.log('End')
💡 Hint
Check the 'Call Stack' column at step 3 in the execution_table.
At which step does the event loop move the callback from the task queue to the call stack?
AStep 8
BStep 5
CStep 7
DStep 9
💡 Hint
Look for 'Move callback to call stack' in the 'Event Loop Action' column.
If the call stack was busy at step 7, when would the callback run?
ABefore the synchronous code finishes
BImmediately at step 7
CAfter the call stack becomes empty
DNever
💡 Hint
Refer to the explanation in key_moments about event loop waiting for empty call stack.
Concept Snapshot
JavaScript runs synchronous code on the call stack.
Async tasks go to Web APIs and then to the task queue.
The event loop moves callbacks to the call stack when it's empty.
This ensures non-blocking, ordered execution of async code.
Full Transcript
JavaScript executes code on a single call stack. When it encounters asynchronous tasks like setTimeout, it sends them to Web APIs to wait. Once the async task finishes, its callback is placed in the task queue. The event loop constantly checks if the call stack is empty. If it is, it moves the callback from the task queue to the call stack to execute it. This process allows JavaScript to handle asynchronous operations without blocking the main thread. In the example, 'Start' and 'End' print first because they are synchronous. The 'Timeout' callback runs last, even with zero delay, because it waits for the call stack to clear.

Practice

(1/5)
1. What is the main role of the JavaScript event loop?
easy
A. To manage execution of multiple tasks without stopping the program
B. To compile JavaScript code into machine code
C. To store variables and functions in memory
D. To style HTML elements dynamically

Solution

  1. Step 1: Understand event loop purpose

    The event loop allows JavaScript to handle many tasks smoothly by managing task execution order.
  2. Step 2: Compare options with event loop role

    Only To manage execution of multiple tasks without stopping the program describes managing multiple tasks without stopping, which matches the event loop's job.
  3. Final Answer:

    To manage execution of multiple tasks without stopping the program -> Option A
  4. Quick Check:

    Event loop = manages tasks smoothly [OK]
Hint: Event loop runs tasks one by one without freezing [OK]
Common Mistakes:
  • Confusing event loop with code compilation
  • Thinking event loop handles styling
  • Believing event loop stores variables
2. Which of the following is the correct syntax to schedule a function to run after the current code using the event loop?
easy
A. setTimeout(myFunction, 0);
B. runLater(myFunction);
C. delay(myFunction, 0);
D. executeAfter(myFunction);

Solution

  1. Step 1: Identify standard JavaScript function for scheduling

    setTimeout is the built-in function to schedule code after current execution.
  2. Step 2: Check options for correct syntax

    Only setTimeout(myFunction, 0) is valid JavaScript syntax to schedule a function immediately after current code.
  3. Final Answer:

    setTimeout(myFunction, 0); -> Option A
  4. Quick Check:

    Use setTimeout(fn, 0) to schedule tasks [OK]
Hint: Remember setTimeout(fn, 0) delays after current code [OK]
Common Mistakes:
  • Using non-existent functions like runLater or delay
  • Omitting the delay argument in setTimeout
  • Confusing setTimeout with synchronous calls
3. What will be the output of the following code?
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
console.log('End');
medium
A. Start
Timeout
End
B. Start
End
Timeout
C. Timeout
Start
End
D. End
Start
Timeout

Solution

  1. Step 1: Understand synchronous and asynchronous order

    console.log('Start') runs first, then setTimeout schedules 'Timeout' to run later, then console.log('End') runs immediately.
  2. Step 2: Determine output order

    'Start' prints, then 'End' prints, then after current code finishes, 'Timeout' prints from the event loop.
  3. Final Answer:

    Start
    End
    Timeout
    -> Option B
  4. Quick Check:

    Sync logs first, then setTimeout logs [OK]
Hint: setTimeout runs after current code finishes [OK]
Common Mistakes:
  • Assuming setTimeout runs immediately
  • Mixing order of synchronous logs
  • Ignoring event loop delay
4. Identify the error in this code snippet related to the event loop:
setTimeout(() => {
  console.log('Hello');
}, '1000');
medium
A. setTimeout requires three arguments
B. Arrow functions cannot be used with setTimeout
C. Missing parentheses after console.log
D. The delay should be a number, not a string

Solution

  1. Step 1: Check setTimeout delay argument type

    The delay argument must be a number, but here it is a string '1000'.
  2. Step 2: Understand effect of wrong type

    Passing a string may cause unexpected behavior or be coerced, but best practice is to use a number.
  3. Final Answer:

    The delay should be a number, not a string -> Option D
  4. Quick Check:

    Delay must be number in setTimeout [OK]
Hint: Use number for delay in setTimeout, not string [OK]
Common Mistakes:
  • Using string instead of number for delay
  • Thinking arrow functions are invalid here
  • Assuming setTimeout needs 3 arguments
5. You want to run two functions, first() and second(), so that second() runs only after first() finishes, but first() contains asynchronous code using setTimeout. How can you ensure second() runs after first() completes all its tasks?
hard
A. Use two separate setTimeout calls with the same delay
B. Call second() immediately after calling first()
C. Call second() inside the callback of setTimeout in first()
D. Use a loop to wait until first() finishes

Solution

  1. Step 1: Understand asynchronous behavior of setTimeout

    setTimeout runs code later, so code after first() runs immediately without waiting.
  2. Step 2: Ensure second() runs after first()'s async code

    To guarantee order, call second() inside the setTimeout callback in first(), so it runs after the async task.
  3. Final Answer:

    Call second() inside the callback of setTimeout in first() -> Option C
  4. Quick Check:

    Chain async calls inside callbacks to keep order [OK]
Hint: Put second() inside first()'s async callback [OK]
Common Mistakes:
  • Calling second() immediately after first() ignoring async
  • Using multiple setTimeouts with same delay expecting order
  • Trying to block with loops instead of callbacks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard