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

190
Views
Custom Asynchronous function in JavaScript not working
console.log('Start');
const myFunc = async () => {
 for(let i=0; i<10000000000000; i++){}
 console.log('After for loop');
}
myFunc();
console.log('end');

I want async behaviour using async/await. I want my function to pass the entire function to an event loop same as SetTimeout, SetInterval does so that my main thread can continue to do the rest unless that heavy functionality is running behind the scene.

Expected Output: Start, end, After for loop

Current Output: Start, AFter for loop, end

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

0

Your understanding of asynchronous javascript code is not correct.

Function passed to setTimeout doesn't execute in the background - it executes on the main thread and while that function is executing, nothing else executes.

It's just that the callback function of setTimeout is pushed in to the call stack after the timer has expired and the call stack is empty. This is why other code can execute before the callback function of setTimeout executes.

Some functions provided by the browser such as HTTP requests happen in the background and once they are complete, Javascript will invoke our callback function and once that callback function starts executing, it blocks everything else from executing until that function is popped off the call stack.

Putting your code inside an async function doesn't makes your code asynchronous; it will execute synchronously until the first await expression. (Promises do not make anything asynchronous. They are just a notification mechanism that notifies you of either successful completion or a failure of something that is already asynchronous.)

What you need is another thread that executes the long running code without blocking the main thread. You can do this using a web worker in the browser or worker thread in NodeJS.

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!