在计数器上设置间隔问题

Set Interval Issue on Counter

我需要在 div 元素中设置一个简单的计数器,我已经完成了下面代码的简化版本,但是计数器没有触发,我不知道为什么不工作

Codepen 在这里:https://codepen.io/emilychews/pen/rzJXpB

代码如下。

JS

var div1 = document.getElementById("div1");

function theCounter() {
  var counter = 0;
  div1.innerHTML = counter;
  counter++;

}

setInterval(theCounter, 1000);

CSS

#div1 {
width: 50px;
height: 50px;
background: blue;
color: white;
}

HTML

<div id="div1"></div>

计数器确实触发了,但您每次调用它时都会重置它的值。您可以将 counter 变量从 theCounter 函数中拉出以使其工作。

var div1 = document.getElementById("div1");
var counter = 0;

function theCounter() { 
  div1.innerHTML = counter;
  counter+=1;

}

setInterval(theCounter, 1000);

这是更新的笔:https://codepen.io/Nisargshah02/pen/mMXNjp