使用setInterval循环

时间:2018-01-01 01:42:55

标签: javascript

我正在尝试使用带有循环函数的JavaScript和setInterval创建一个从10到0的计数器,但这对我不起作用:

function count() {
  var i;

  for (i = numbers.textContent; 0 <= i; i--) {
    numbers.textContent = i;
  }

}

setInterval(count, 1000);
<div id="countDown">10</div>

3 个答案:

答案 0 :(得分:0)

这应该有效:

parseInt(numbers.textContent)

还有更多:

  1. 您需要一个全局变量。
  2. 您不需要for循环。
  3. 改变条件。
  4. <div id="countDown">10</div>
    <script>
      var numbers = document.getElementById('countDown');
      var interval = setInterval(count, 1000);
      function count() {
        var count = parseInt(numbers.textContent);
        count--;
        if (count == 0) {
          clearInterval(interval);
        }
        numbers.textContent = count;
      }
    </script>

    如果您想通过循环查看,可以使用setTimeout

    <div id="countDown">10</div>
    <script>
      var numbers = document.getElementById('countDown');
      function count() {
        var count = parseInt(numbers.textContent);
        count--;
        numbers.textContent = count;
      }
      for (var i = 1; i <= parseInt(numbers.textContent); i++)
        setTimeout(count, 1000 * i);
    </script>

答案 1 :(得分:0)

你正在setInterval

中进行for循环

var numbers = document.getElementById('countDown');

function count() {

    var i;
    if(numbers.textContent>0)
      numbers.textContent=numbers.textContent-1;
    else 
      clearInterval(handle);
    /*for(i=numbers.textContent; 0<=i; i--){
        console.log(i)
        numbers.textContent= i;
    }*/

}


var handle= setInterval(count, 1000);
<div id="countDown">10</div>

答案 2 :(得分:0)

the first time count is called, the for loop will run till numbers.textContent is 0(and it's so fast that your eyes just missed that change on the page), and the 2nd call, 3rd call is just iterate around 0, nothing is changed.

BTW, after your counting is finished(or maybe you should give it a stop condition, reference to the DOC), you should unregister the interval, cause it never end by default.