达到“0”时停止倒计时

时间:2013-04-18 16:13:57

标签: javascript

我希望在达到0时停止此计数器,任何人都可以帮助我吗?

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

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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>

答案 2 :(得分: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);

on jsfiddle

答案 3 :(得分: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();