为什么setTimeout会立即触发? [英] Why does setTimeout trigger instantly?
问题描述
我发现这个 setTimeout()
W3学校的方法示例,注意到我无法解释的事情。例如:
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?
推荐答案
不应该是一样的吗?
shouldn´t it be the same?
不,完全没有。
setTimeout( alertFunc,3000)
将 alertFunc
(对函数的引用)的值传递到 setTimeout
。 setTimeout
存储该函数引用以便在三秒后调用它。
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)
调用 alertFunc
,立即传递返回值进入 setTimeout
。正好 foo(bar())
调用 bar
并将其返回值传递给 foo
。
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
.
这篇关于为什么setTimeout会立即触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!