正在创建计数器

Creating a counter

本文关键字:计数器 创建      更新时间:2023-09-26

我正在创建一个计数器,但我很难制作它。计数器的目标是,每过一秒,数字就会增加170。正如你在下面看到的,这个数字没有加起来,而是在一条新的线上生成的,主要是因为我不知道如何使它加起来。像这个来自《经济学人》的时钟

<!DOCTYPE html>
<html>
<body>
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
<script>
function counterFunction() {
setTimeout(function () {
    var text = "";
    var i = 170;
    while (i < 3500) {
        text += "<br>The number is " + i;
        i+=170;
    }, 1000) }
document.getElementById("counter").innerHTML = text;
}
</script>
</body>
</html>

关于我如何做到这一点以及我的代码有什么问题,有什么想法吗?

不要使用内联JavaScript(HTML元素属性中的JavaScript),这对可维护性和可读性来说非常糟糕。

你似乎对超时、间隔和循环的工作方式有一个误解,你想要的是一个间隔。

在事件侦听器函数之外定义一个计数变量,然后在间隔的每次迭代中,将计数变量递增一,并将该数字乘以170。

我在里面添加了一点,在点击按钮后隐藏按钮,只是为了阻止用户重新启动计数器。

var clicker = document.getElementById('clicker');
var counter = document.getElementById('counter');
var count = 0;
clicker.onclick = function() {
  setInterval(function () {
    counter.textContent = "The number is " + ++count * 170;
  }, 1000);
  clicker.style.display = 'none';
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button id="clicker">See it now</button>
<p id="counter"></p>

http://jsfiddle.net/mblenton/Le4vxzrn/2/

function counterFunction() {
    var text = ""; var i = 170;  var delay = 0;  var k = 1;
    while (i < 3500) {
        text = "The number is " + i;
        i += 170;
        delay = k * 1000;
        doSetTimeout(text, delay);
        k++; 
   }
 }
function doSetTimeout(text, delay) {
  setTimeout(function () {
    document.getElementById("counter").textContent = text;
 }, delay);
}

您需要使用setInterval,而不是setTimeout`。请注意,如果您单击该按钮,它将重置您的计时器。

您还需要在Interval的范围之外声明var ivar text,否则它们也将在每次迭代中重置。

您的代码有一些错误。除其他外:

  1. 您的i变量声明在错误的位置以供重用
  2. 你的右大括号放错了回调函数的位置
  3. 您使用的是同步运行的while循环,而您实际上只想使用setInterval调用

这应该有效:

function counterFunction() {
  var i = 170;
  var text = "";
  var interval = setInterval(function () {
    text += "<br>The number is " + i;
    i+=170;
    document.getElementById("counter").innerHTML = text;
    if (i >= 3500) {
      clearInterval(interval);
    }
  }, 1000); 
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>

好的,所以加法器变量应该在超时函数之外声明,因为如果不是,则替换该值。你应该使用setInterval

var p =0;
function counterFunction(){
setInterval(function(){ p+=170;
console.log('value of p '+p);
 }, 3000);
}

如果你不想自己滚,这里有个不错的柜台http://keith-wood.name/countdown.html