为什么setInterval回调只执行一次? [英] Why does the setInterval callback execute only once?

查看:868
本文介绍了为什么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回调只执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆