0

Hello I am relatively new to javascript and node.js and I was looking into how the event loop worked as well as asynchronous programming When I ran this code

function time(ms){
    return new Promise((resolve) =>{
        setTimeout(resolve,time)
    })
}

async function foo(){
    await time(2000)
    console.log("hi ")
    await time(2000)
    console.log("hello")
    await time(1000)
    console.log("bar")


}
foo()
console.log("a")
setTimeout(()=> console.log("b"),10)

The output was

a
hi 
hello
b
bar

when I expected it to be

a
b
hi  
hello  
bar  

Then when I changed the last line to

setTimeout(()=> console.log("b"),3000)

I thought the output would be

a
hi  
b  
hello   
bar    

but it was

a
hi
hello  
bar  
b  

Now I think there's something about the event loop that I'm not understanding because based on my understanding of the task queue and call stack my outputs should be correct but they aren't.

1
  • 1
    You should use setTimeout(resolve, ms), not setTimeout(resolve, time) Commented Aug 20, 2021 at 2:53

1 Answer 1

1

You have a typo in your time function Instead of

setTimeout(resolve,time)

you should write

setTimeout(resolve,ms)

Small explanation. In your current realization, you try to setTimeout(...) to NaN msec, 'cause variable time has type Function and cast to NaN

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.