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

85
Views
Async/Await with setTimeout works well but not with custom delay

When I run an example that I found on the internet which uses setTimeout, it works fine. But when I replace setTimeout with a long running for loop the output appears after delay. Do we have to use a factory made asynchronous function all the time?

Original code:

const doSomethingAsync = () => {
    return new Promise(resolve => {
        setTimeout(() => resolve('I did something'), 3000)})
        }

    const doSomething = async () => {
        console.log(await doSomethingAsync())
    }
console.log('Before')
doSomething()
console.log('After')

Code with custom delay:

const doSomethingAsync = () => {
    return new Promise(resolve => {
        for(let i=0;i<4000000000;i++){}
        resolve("I did something!");
        })
        }

    const doSomething = async () => {
        console.log(await doSomethingAsync())
    }
console.log('Before')
doSomething()
console.log('After')

When the custom code runs the output of After happens after the delay, whereas in the original code After appears immediately.

Edit: By the way the question at Why isn't Javascript async function immediately returning? is similar but the order doesn't change in my case, timing does.

about 4 years ago · Juan Pablo Isaza
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!