0

I'm new to Javascript and trying to understand async programming. So I wrote the below code in chrome developer tools workspace -

console.log("hi1");
setTimeout(console.log("hi-async"),1000);
console.log("hi3");

The out put I was expecting was -

hi1
hi3
hi-async

Instead, the console printed following, without the 1 second delay (all at once) -

hi1
hi-async
hi3

So basically, the setTimeout function was executed synchronously! Can someone tell me why that's the case? I thought setTimeout is an async function and will always be executed asynchronously. Am I wrong? Thanks!

  • You are calling `console.log()` and passing its return result as the first argument to `setTimeout()` (which is `undefined`). The `setTimeout()` method should be passed a function that it will execute – Nick Parsons Jun 09 '22 at 23:51
  • `setTimeout` expects an callback function and the time. You pass `undefined` and time. If you execute `console.log()` it returns undefined – bill.gates Jun 10 '22 at 00:06
  • Just to clarify what the above commentors mean, all you need to do is change your call to setTimeout to: setTimeout(() => console.log("hi-async"),1000); – Rasmus Søborg Jun 10 '22 at 00:58

0 Answers0