我想在计数器达到 0 时停止它,有人可以帮我吗?
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
我想在计数器达到 0 时停止它,有人可以帮我吗?
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
您使用 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);
<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>
尝试这个
<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);
单程;
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();