创建一个柜台

时间:2015-10-27 19:11:07

标签: javascript loops time while-loop

我正在创建一个计数器,而且我很难做到。 该计数器的目标是,无论如何,一个数字将增加170。 正如你在下面看到的那样,这个数字并没有加起来并且是在新的一行上进行的,主要是因为我不知道如何使它加起来。像The Economist

这样的时钟
<!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>

关于如何制作这个以及我的代码有什么问题的任何想法?

5 个答案:

答案 0 :(得分:5)

不要使用内联JavaScript(HTML元素属性中的JavaScript),这对可维护性和可读性来说太可怕了。

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

在事件侦听器函数之外定义一个count变量,然后在每个间隔迭代中将count变量增加1并将该数字乘以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>

答案 1 :(得分:1)

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);
}

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

var p =0;

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

如果你不想自己在这里滚动是一个很好的反击 http://keith-wood.name/countdown.html

答案 4 :(得分:0)

您的代码存在一些问题。除其他外:

  1. 您的i变量被声明在错误的位置以便重复使用
  2. 你的结束括号位于回调函数的错误位置
  3. 您正在使用同步运行的while循环,而您确实只想使用setInterval来电。
  4. 这应该有效:

    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>

相关问题