How to repeatedly update the contents of a
by only using JavaScript?

后端 未结 1 1520
孤街浪徒
孤街浪徒 2020-12-22 14:23

At the moment I want to convert this code so that it doesn\'t show the value of i in prompt boxes. I need it to repeatedly update the value of i inside a dedicated <

1条回答
  •  有刺的猬
    2020-12-22 15:20

    Do use getElementById() to get the element.

    Do use innerHTML to set the text content.

    Don't use setInterval in loops (unless you mean to) because that will cause the callback you give to the setInterval to be executed n number of times every timeout.

    Do use clearInterval to stop the interval from executing when you are done.

    var el = document.getElementById("timer");
    var i = 0;
    
    var interval = setInterval(function() {
      el.innerHTML = i++;
      if (i > 10) {
        clearInterval(interval);
      }
    }, 1000);


    Alternatively, use setTimeout and avoid setInterval and clearInterval. Then you can simply not make a new timeout when you are above your maximum count.

    var el = document.getElementById("timer");
    var i = 0;
    
    function counter() {
      el.innerHTML = i++;
      if (i <= 10) {
        setTimeout(counter, 1000);
      }
    }
    
    counter();

    0 讨论(0)
提交回复
热议问题