0

I was recently asked to debug the following block of code and ask what would be the output:

setTimeout(function() {
    console.log(1);
}, 20);
setTimeout(function() {
    console.log(2);
}, 10);
setTimeout(function() {
    console.log(3);
}, 0);
setTimeout(console.log(4), 30);
console.log(5);

According to my understanding, setTimeout() only takes callback functions and a delay time and so setTimeout(console.log(4), 30); would give an error of some sort (since this setTimeout only takes an expression) and nothing would be logged in the console. But when tested in browser console, the output was

4
5
3
2
1

Any help would be appreciated in explaining why setTimeout(console.log(4), 30); just prints out the 4 and moves onto console.log(5);.

  • 1
    Possible duplicate of [Why is my function call that should be scheduled by setTimeout executed immediately?](https://stackoverflow.com/questions/2037203/why-is-my-function-call-that-should-be-scheduled-by-settimeout-executed-immediat) – Herohtar Apr 13 '18 at 20:55
  • Because `console.log(4)` is immediately invoked. IOW: The timeout becomes a No Op. – Keith Apr 13 '18 at 20:55

2 Answers2

2

It does this because console.log(4) is just an expression that is immediately executed (printing 4 to the console).

The syntax is allowed because if the return value were a function then that function would be the callback for the timer as in this example:

function returnFunction(){
  return function(){
    console.log("hello");
  };
}

// returnFunction will be executed immediately (because of the () after the 
// function name) and it will return, yet another function. That returned 
// function is the one that will be called after a one second delay.
setTimeout(returnFunction(), 1000);

It is possible to set up a timer by just passing code to execute (rather than code to execute wrapped in a callback function), but you must pass the code as a string:

setTimeout("console.log(4)", 2000);

However, this syntax is highly discouraged for security and performance reasons.

See details on setTimeout() here.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Every function argument is an expression. Therefore

   setTimeout(console.log(4), 10)

will execute console.log(4) which logs 4 and then evaluates to undefined, and

  setTimeout(undefined, 10)

does nothing.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151