为什么 setTimeout 需要匿名函数才能工作? [英] Why does setTimeout require anonymous function to work?
问题描述
我正在阅读 StackOverflow 上的一个答案这里,其中解释了如何使用 setTimeout 在网页.但是,我想知道为什么 setTimeout 需要匿名函数才能工作.考虑以下代码:
I was reading an answer on StackOverflow here that explained how to use setTimeout to create a sort of recurring loop on a webpage. However, I am wondering why setTimeout requires an anonymous function to work. Consider the following code:
trainingTimer(60,0);
function trainingTimer(duration,c) {
document.getElementById("timer").innerHTML = "Time left: "+(duration-c);
if(duration==c) {
alert("Time is up!");
}
else {
window.setTimeout(trainingTimer(duration,c+1),1000);
}
}
我根据上面链接的答案写了这个,但是当它运行时,它会一次循环所有 60 个 trainingTimer
调用,并立即在我的网页上显示剩余时间:0".但是,如果我修改
I wrote this based off the answer that I linked above, however when it runs it loops through all 60 trainingTimer
calls at once, and immediately displays "Time left: 0" on my web page. However, if I modify
window.setTimeout(trainingTimer(duration,c+1),1000);
并将 trainingTimer(duration,c+1)
包裹在一个匿名函数中
and wrap trainingTimer(duration,c+1)
in an anonymous function like so
window.setTimeout(function() {trainingTimer(duration,c+1)},1000);
然后代码运行得很好.
我想知道为什么我必须将命名函数包装在匿名函数中才能使 setInterval 正常工作.感谢大家的帮助.
I am wondering why I have to wrap a named function inside an anonymous function in order for setInterval to work properly. Thanks for all the help.
推荐答案
这个
window.setTimeout(trainingTimer(duration,c+1),1000);
与
var result = trainingTimer(duration,c+1);
window.setTimeout(result,1000);
它获取执行方法的结果并赋值.
It takes the result of the executed method and assigns it.
而且由于训练计时器方法没有返回任何内容.你的代码基本上是这样的
And since training timer method returns nothing. Your code is basically this
trainingTimer(duration,c+1);
window.setTimeout(undefined, 1000);
这篇关于为什么 setTimeout 需要匿名函数才能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!