Suppose I wrote a function:

function foo() { alert("Hello, world!"); } 

Why when I try to call her after a while, is she called immediately instead?

 setTimeout(foo(), 10000); 

And the same with event handlers? I tried to do this:

 el.onclick = foo(); el.addEventListener("click", foo()); createButton({ name: "show alert", onClick: foo(), }); 
  • five
    I have several times stumbled upon this error on the site and every time I fought a desire to help and unwillingness to spend time on such garbage. Now such questions can be closed as duplicates. - Pavel Mayorov

1 answer 1

You may have written brackets around the function name - foo() - randomly. And perhaps you think that it is by these brackets that the function differs from the variable. In any case, the error is hidden here.

Briefly: remove the extra brackets and everything will work.


Javascript evaluates expressions from the inside out (like many other languages). Obvious examples from mathematics: in the expression 2 + 2 * 2 , multiplication is first performed, and then addition, and the opposite in expression (2 + 2) * 2 .

When you write foo() , it is a function call operator. This is the same part of the expression as any mathematical operation. And if somewhere inside the expression there is a call to foo() , then the function foo will be called regardless of what is written outside.

So, in the example setTimeout(foo(), 10000); foo() is called first , and then the result of the foo() call (usually it's some kind of undefined ) is passed to setTimeout : setTimeout(undefined, 10000) . From the point of view of the Javascript interpreter, this is not a mistake: he does not know what foo , he just obediently does what you told him.

If you do not need to call a function, then you do not need to call it. Just remove the parentheses around the function name - and now it is passed as is, without calling:

 setTimeout(foo, 10000); el.onclick = foo; el.addEventListener("click", foo); createButton({ name: "show alert", onClick: foo, }); 

Call it in another place when the time comes. (By the way, such a function passed somewhere is usually called a callback, callback, or callback function).

If you are concerned about the question of how in this case the interpreter will distinguish the function from the variable, then the answer to it - and he does not need to distinguish them, the function name is a kind of variable name.