TheWandererr TheWandererr - 1 year ago 103
Javascript Question

Why does setTimeout trigger instantly?

I found this

method example on W3 Schools and noticed something that I cannot explain. The example is:

myVar = setTimeout(alertFunc, 3000);

...which works fine. But when I change it to

myVar = setTimeout(alertFunc(), 3000);

...the alert triggers instantly. Why? Shouldn't it be the same?

Answer Source

shouldn´t it be the same?

No, not at all.

setTimeout(alertFunc, 3000) passes the value of alertFunc (a reference to a function) into setTimeout. setTimeout stores that function reference in order to call it three seconds later.

setTimeout(alertFunc(), 3000) calls alertFunc, immediately, and passes its return value into setTimeout. Exactly the way foo(bar()) calls bar and passes its return value into foo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download