3

我想在计数器达到 0 时停止它,有人可以帮我吗?

function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=0) {
    }
    i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
4

4 回答 4

6

您使用 clearInterval 函数:

var id;
function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=1) {
        clearInterval(id);
    }
    i.innerHTML = parseInt(i.innerHTML)-1;
}
id = setInterval(countdown,1000);
于 2013-04-18T16:18:14.887 回答
2
<html >
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="counter">5</div>

<script type="text/javascript">
function countdown() {
    var i = document.getElementById('counter');
    i.innerHTML = parseInt(i.innerHTML)-1;
    if (parseInt(i.innerHTML)==0) {
       clearInterval(timerId);
    }
}
var timerId = setInterval(function(){ countdown(); },1000);
</script>
</body>
</html>
于 2013-04-18T17:53:25.807 回答
1

尝试这个

<div id="counter">10</div>

var i = document.getElementById('counter'),
    sId;

function countdown() {
    var count = parseInt(i.textContent, 10);

    if (count < 1) {
        clearInterval(id);
    }

    i.textContent = count - 1;
}

sId = setInterval(countdown, 1000);

jsfiddle上

于 2013-04-18T16:25:00.230 回答
1

单程;

function countdown() {
  var el = document.getElementById('counter');
  var value = parseInt(el.innerHTML, 10);

  var intervalId = setInterval(function() {
    el.innerHTML = --value;
    if (value === 0) {
       clearInterval(intervalId);      
    }
  }, 1000);
};

countdown();
于 2013-04-18T16:28:04.383 回答