Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
How does an async function called with await can block the event loop?

In the following code, the 'Hey, timeout executed!' is only printed after the loop in the longLoop function is finished.

setTimeout(() => console.log('Hey, timeout executed!'), 100);

let longLoop = async () => {
    for (i = 0; i < 1000000000; i++) {
    }
}

let exec = async () => {
    await longLoop();

    console.log('Loop finished')

}

exec()

However, when I change the longLoop to have an await inside it, the 'Hey, timeout executed!' will print as soon as the await in the loop is reached, like in the following:

setTimeout(() => console.log('Hey, timeout executed!'), 100);

let longLoop = async () => {
    for (i = 0; i < 1000000000; i++) {
        await new Promise(r => setTimeout(r, 100));
    }
}

let exec = async () => {
    await longLoop();

    console.log('Loop finished')

}

exec()

Why does in the first example the event loop seems to be blocked even if I call the longLoop from the exec using an await? And why it doesn't get blocked in the second example just by using an await inside the loop?

I'm just starting in JavaScript, so I thought that just by a function being async and being called with an await inside another async function, it would be executed in a way that the event loop would not be blocked. Due to that, I'm having kinda a hard time to understand the flow of execution.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is a case of microtasks vs (macro)tasks. Promises and async/await enter the microtask queue. setTimeout callbacks enter the (macro)task queue. microtasks get run before (macro)tasks (when the stack is empty to be precise), that's why you see the async/await functions get executed before the setTimeout callback

See also: Difference between microtask and macrotask within an event loop context https://stackoverflow.com/a/71195496/4651083

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!