本文介绍了为什么 setInterval 回调只执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个计数器,但我想让它永远运行,这真的很简单,我在这里做错了什么?
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)
推荐答案
您使用函数调用而不是函数引用作为 setInterval 的第一个参数.这样做:
You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:
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)
这篇关于为什么 setInterval 回调只执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!