0
const sayHello = function () {
  console.log("hello");
};

sayHello;
sayHello();

setTimeout(sayHello, 1000);
setTimeout(sayHello(), 1000);

I'm a little confused as to why line 5 'does nothing' but also doesn't throw an error, whereas line 8 runs as expected but line 9 throws the invalid callback error. I'm running this code is Visual Studio Code if it makes a difference.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • ok, so how `setTimeout` works is that it takes arguments like `(Function, Number)` and it will try to execute the function when the number in time is reached. The problem is that `sayHello` is a function whereas `sayHello()` is undefined.. this is because `sayHello()` is the executed form of the function therefore it's equal to what it returns, and in your case, NOTHING – The Bomb Squad May 05 '21 at 21:15
  • `sayHello;` does nothing because it's a reference to a function. `sayHello();` on the other hand calls the function (logging "hello"). When using setTimeout though, you're supposed to pass a function as first argument, which you're doing the first time. The second time, you're calling the function rightaway and passing the return value to setTimeout, however since the function doesn't return anything, the last line is equivalent to `setTimout(undefined, 1000)`, hence the error. –  May 05 '21 at 21:17
  • To really get what's happening, it is important to understand that when a line like `setTimeout(sayHello(), 1000);` is encountered, everything except `sayHello()` is completely ignored until the function call is resolved. To better understand the order in which things happen and how they happen, try running this line (in a browser): `alert(prompt("enter your name:") + " is " + prompt("enter your age:") + " years old")` –  May 05 '21 at 21:22
  • [What is the difference between a function call and function reference?](https://stackoverflow.com/q/15886272) – VLAZ May 05 '21 at 21:23

1 Answers1

2

When you use () after a function name, you're executing the function. But without it, you're referencing the function instead. That is why line 5 doesn't do anything. The function is not being executed. But line 6 on the other hand is executing the function, which should print "hello" to the console.

The setTimeout needs a function reference (the callback function), to let it know what to execute after the 1000 ms has passed.

So typing setTimeout(sayHello(), 1000) executes the sayHello function directly instead of providing it as a callback. So that will not work as you intend.

Typing setTimeout(sayHello, 1000), you're instead providing the function reference instead, to the setTimeout will know what function to execute after the 1000 ms has passed. This is the correct way to do it.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Phoenix1355
  • 1,589
  • 11
  • 16