setInterval回调只运行一次 [英] setInterval callback only runs once

查看:155
本文介绍了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天全站免登陆