TheWandererr TheWandererr - 10 days ago 8
Javascript Question

Why does setTimeout trigger instantly?

I found this

setTimeout()
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

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.

Comments