帮我调试这段代码。该按钮应在单击时打开一个链接,主页上的访问按钮将被禁用,其值将成为一个计时器。第一次点击没有问题,但是当计时器用完并再次点击按钮时,时钟的速度就会加快。请帮我。
<html>
<head>
<script type = "text/javascript">
var t;
var isTimeron = false;
var counter = 0;
function disableButt()
{
document.getElementById("but1").disabled = true;
}
function enableVisit()
{
document.getElementById("but1").disabled = false;
}
function stopMe()
{
isTimeron = false;
clearTimeout(t);
}
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
function startMe() {
if (!isTimeron)
{
counter = 10;
isTimeron = true;
countdown();
}
}
</script>
<body>
<a href='' target = '_blank'><input type = "button" id = "but1" value = "VISIT" style="background:#83FF59; font-weight:bold;"
onclick = "startMe(); disableButt();"/></a>
</body>
</html>
最佳答案
您没有停止第一个计时器。
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
计数器低于零,您通过仍然调用 setTimeout 来调用 stopMe()。您现在有两个计时器正在运行。
直接改成
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
return;
}
t = setTimeout("countdown();", 1000);
}
小建议避免在 setTimeout 中使用字符串。
setTimout(countdown, 1000);
比较好
关于javascript - 当时的 JavaScript 提高了第二个循环的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106471/