I am just starting to learn javascript while reading a book about node.js. In one of the first examples it shows a high-order function:
setTimeout(function () {
console.log('2000 milliseconds have passed since this demo started');
}, 2000);
This works when I run it in the REPL. It waits 2 seconds and then writes the string I gave it.
So I tried doing something that I expected would produce the same output:
setTimeout(console.log('2000 milliseconds have passed since this demo started'),2000);
This printed the string out immediately. I am guessing that the setTimeout still waited and then did nothing at the end of the 2 seconds. It just printed the string out first for some reason.
I played around with it a little more and created another function that just prints a string:
function tester() {
console.log('tester function ran');
}
I then called this function inside of setTimeout:
setTimeout(tester(),2000);
It still printed the string in tester() out first and then waited 2 seconds and did nothing else.
I then tried removing the parenthesis:
setTimeout(tester,2000);
This "worked". It waited 2 seconds and then printed out the string in tester().
My question now is what is the difference between tester() and tester in this context? And does this mean that I can't pass arguments to a function inside of the high-order function setTimeout()? If so, why?