我试图显示2个按钮用于3分钟的计时器,但问题是我的第二个计时器工作正常但是第一个计时器没有,即使我删除第二个计时器仍然存在第一个问题计时器。两个定时器的代码相同只是变量不同
<table>
<tr class="odd">
<td></td>
<th scope="row"><div class="timer">
<time id="countdown"></time>
</div>
</th>
<td></td>
<td><form name="form"><input type="button" name="start" id="colourButton" value="Start Time!" onclick="showDiv()"/></form></td>
</tr>
<tr class="odd">
<td></td>
<th scope="row"><div class="timer">
<time id="countdown2"></time>
</div>
</th>
<td></td>
<td><form name="form1"><input type="button" name="start1" id="colourButton2" value="Start Time!" onclick="showDiv2()"/></form></td>
</tr>
</table>
<script>
function showDiv() {
document.form.colourButton.disabled = true;
var countdownTimer = setInterval('secondPassed()', 1000);
}
var seconds = 180;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
window.alert("Times Up");
} else {
seconds--;
}
}
function showDiv2() {
document.form1.colourButton2.disabled = true;
var countdownTimer1 = setInterval('secondPassed1()', 1000);
}
var seconds1 = 180;
function secondPassed1() {
var minutes1 = Math.round((seconds1 - 30)/60),
remainingSeconds1 = seconds1 % 60;
if (remainingSeconds1 < 10) {
remainingSeconds1 = "0" + remainingSeconds1;
}
document.getElementById('countdown2').innerHTML = minutes1 + ":" + remainingSeconds1;
if (seconds1 == 0) {
clearInterval(countdownTimer1);
//form1 is your form name
window.alert("Times Up");
} else {
seconds1--;
}
}
</script>
答案 0 :(得分:0)
它不会按预期工作(没有两个定时器),因为你试图取消设置一个无法找到的间隔,它会产生错误,如未捕获的ReferenceError:未定义countdownTimer1 (Chrome)
您必须更改行
var countdownTimer = setInterval('secondPassed()', 1000);
和
var countdownTimer1 = setInterval('secondPassed1()', 1000);
到
countdownTimer = setInterval('secondPassed()', 1000);
和
countdownTimer1 = setInterval('secondPassed1()', 1000);
这使得变量 countdownTimer 和 countdownTimer1 在脚本的全局范围内可用,然后它就能正常工作。