TheWandererr TheWandererr - 1 month ago 25
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?


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.