Javascript 为什么 setInterval 回调只执行一次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10182714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does the setInterval callback execute only once?
提问by computer_smile
I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?
我有我制作的这个计数器,但我希望它永远运行,这真的很简单,我在这里做错了什么?
function timer() {
console.log("timer!")
}
window.setInterval(timer(), 1000)
回答by Koen Peters
You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:
您使用函数调用而不是函数引用作为 setInterval 的第一个参数。像这样做:
function timer() {
console.log("timer!");
}
window.setInterval(timer, 1000);
Or shorter (but when the function gets bigger also less readable):
或者更短(但当函数变大时,可读性也会降低):
window.setInterval( function() {
console.log("timer!");
}, 1000)
回答by Bakudan
setInterval
and setTimeout
mustbe used with callbacks, like:
setInterval
并且setTimeout
必须与回调一起使用,例如:
setInterval(timer, 1000);
or unnamed functions:
或未命名的函数:
setInterval( function() { console.log("timer!"); }, 1000 );
Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() )
you are passing the result of the function.
为什么您的代码不起作用 - 当您将一个函数作为参数传递给另一个带括号的函数时,例如doSomething ( someFunc() )
您正在传递函数的结果。
When the function is passed as object e.g. doSomething ( someFunc )
you are passing a callback. This way someFunc
is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.
当函数作为对象传递时,例如doSomething ( someFunc )
您正在传递回调。这种方式someFunc
作为引用传递,并在调用函数的某处执行。这与其他语言中的函数指针相同。
A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval
.
一个常见的错误是使用w3schools 中显示的这两个函数。这对 进行了隐式调用eval
。