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
  • I must ask now though, what if you wanted to reference the foo function with an argument? e.g. setTimeout(foo(x), 2000). I understand now that this will obviously result in a stack overflow, but is it possible to pass a argument in the first function reference? Commented Jul 9, 2012 at 21:55
  • @ChrisM - Yes, in that case the best thing to do is pass a reference to an anonymous function that then calls the desired function. Like this: setTimeout(function() { foo(x) }, 2000) Commented Jul 9, 2012 at 21:56

lang-js

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