Pankaj Sharma Pankaj Sharma - 23 days ago 6
Javascript Question

why Javascript showing output with setTimeout function sync and async?



for(var i = 2;i >= 1;i--) {
setTimeout(function (i) {
console.log(i);
},1000);
console.log("hii");
}





This code gives me output as


  • hii

  • hii

  • undefined

  • undefined



Where as after using setTimeout in below format gives different output



for(var i = 2;i >= 1;i--) {
setTimeout(print(i),5000);
console.log("hii");
}
function print(i) {
console.log(i);
}





This code gives me output as


  • 2

  • hii

  • 1

  • hii



I don't understand why in second case code is executing synchronously.

Answer

Because there you have called the print function, it's not passed as a callback. In this situation, it will complete the execution of print function and then pass the return value as first argument to setTimeout.

This is what you are trying:-

for(var i = 2;i >= 1;i--) {
  setTimeout(print(i),5000);
  console.log("hii");
}
function print(i) {
  return function(){console.log(i)}
}