Home > OS >  setTimeOut inside a function
setTimeOut inside a function

Time:07-25

enter image description here

I'm trying to understand what asyncrounous programming is & from what I learned that the setTimeOut function is asyncrounous which mean that the next code will be executed and when the time elapses the code inside it will be executed , now I know that when I call the test function "second" will be printed first but I don't understand why "third" is printed before "first" , shouldn't it wait for the test function to be executed before it's printed.

function test(){
  setTimeout(() => {
    console.log("first")
  }, 1000);
  console.log("second")
}


test()
console.log("third")

CodePudding user response:

settimeout will execute the code after the amount of time you give pass which is 1 sec on your case

so anything else after it will run despite it in the same scope like in same function or even outside it

Settimeout

CodePudding user response:

well, no setTime is not a promise (don't get confused whit the promise object in js ) when u say i want it for a second from now you can't ever be sure it's depended on scheduling on event loop and how busy the current thread is

CodePudding user response:

So if what you're wanting is to have it wait to print out the result of the timeout before continuing to print "second" you need to do an async await model:

async function test(){

  await setTimeout(() => {
  
    console.log("first");
    
  }, 1000);
  
  console.log(second);
  
}

run();
console.log("third");

Note that the keyword async is necessary to mark a function as async. Then you must use the await keyword before an action that you want to wait for. I hop this helps.

  • Related