Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Why do I have to omit parentheses when passing a function as an argument?

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. 

Answer*

Draft saved
Draft discarded
Cancel
2
  • As an example, try running var foo = (function() { alert("Hello"); }) in your console; then, try running var foo = (function() { alert("Hello"); })() -- notice how the parens at the end of the statement actually invoke the function as soon as it's defined! Commented Jul 9, 2012 at 21:26
  • this makes perfect sense to me now. I was interpreting the two arguments to setTimeout(x,y) as x = what do you want to do and y = how often do you want to do it. To my misunderstanding i wanted to call and execute foo, and do it every 2 seconds. thanks for your answer! Commented Jul 9, 2012 at 21:46

lang-js

AltStyle によって変換されたページ (->オリジナル) /