我目前正在JavaScript中为HTML页面使用一个JavaScript函数。它有一个按钮,允许我在1秒间隔内开始从10到0的倒计时,每次我按下这个按钮,倒计时就应该被重置。然而,在第一个按钮按下后,下一个倒计时会严重地扰乱时间间隔。
var count;
function countdown() {
count = 10;
var repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}<html>
<head>
<title>Page 4</title>
</head>
<body>
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
</body>
</html>
发布于 2016-10-05 09:16:01
在调用倒计时时,可以使用全局变量repeat和重置(如果设置)。
var count,
repeat;
function countdown(){
count = 10;
if (repeat) {
clearInterval(repeat);
}
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}<button style=" display: inline-block; " onclick ="countdown()" >Start Count Down</button>
<div style="display: inline-block;" id="number"></div>
发布于 2016-10-05 09:15:08
您的问题是repeat变量,它只有在countdown中才能定义和访问。
您也可以将其设置为全局的,然后再次单击该按钮时必须清除以前的间隔。
var count, repeat;
function countdown() {
clearInterval(repeat);
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}发布于 2016-10-05 09:15:11
把你的重复放在外面,这样函数减少就可以访问它了。
var count;
var repeat = null;
function countdown(){
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if(count > 0)
{document.getElementById('number').innerHTML = count;
count--;}
else
{clearInterval(repeat);}
}https://stackoverflow.com/questions/39869857
复制相似问题