I am trying to wrap my head around as to why the following code results in a stack overflow when the parentheses are included, but do not when they omitted.
I am calling the function itself as an argument to setTimeout and it works without parantheses, but of course fails when I add them. It was my intuition to add the () after the function. Just hope somebody can clear this up for me. When are parans optional and not?
CASE 1:
var a = 1;
function foo() {
a++;
document.write(a);
setTimeout(foo(), 2000)
}
// RangeError: Maximum call stack size exceeded
CASE 2:
var a = 1;
function foo() {
a++;
document.write(a);
setTimeout(foo, 2000)
}
// parens are omitted on foo function and it works.
This question is usually first asked in reference to
setTimeout
, but I think it's important to point out that the behavior here isn't specific to that function. You simply need to understand what the parenthesis do and what it means to leave them off.Assume the following function:
Consider the following two variable declarations/assignments:
What values do these variables have?
In the first case we're executing the
foo
function and assigning its return value -- the number5
-- toone
. In the second case we're assigningfoo
itself -- more precisely, a reference tofoo
-- totwo
. The function is never executed.With this knowledge and an understanding that
setTimeout
expects as its first argument a reference to a function, it should be obvious why your first case fails, but the second one works.Of course, your problem is exacerbated by the fact that the function you're executing is a recursive call to itself. This will just run forever -- for some definition of forever -- because there's no base case to terminate the recursion.
By writing
you're actually calling foo at that moment. Which of course then calls foo() again...until you stackoverflow.
In case 2 you're effectively passing a "reference" to foo, saying "run this in 2s". Not actually calling foo().
So use parens when you actually want to invoke it. Not when you want to refer to it.