var button1 = document.getElementById("start");
var button2 = document.getElementById("stop");
var timegraph = document.getElementById("ceas");
var time = 0;
var ResetStart = 0;
function Start(){
if (ResetStart==0) {
ResetStart=1;
Running();
button1.innerHTML="Pause";
}
else {
ResetStart=0;
button1.innerHTML="Resume";
clearInterval(myInterval);
}
}
function Reset(){
time = 0;
ResetStart = 0;
button1.innerHTML="Start";
timegraph.innerHTML="00:00:00:00";
}
function OnGoing(){
time++;
var hours = Math.floor(time/100/60/60);
var minutes = Math.floor(time/100/60 % 60);
var seconds = Math.floor(time/100 % 60);
var hundreds = Math.floor(time/10 % 10);
var thousands = time % 10;
if (hours<10){
hours = "0" + hours;
}
if (minutes<10) {
minutes = "0" + minutes;
}
if (seconds<10) {
seconds = "0" + seconds;
}
timegraph.innerHTML=hours + ":" + minutes + ":" + seconds + ":" + hundreds + thousands;
}
function Running(){
if (ResetStart==1){
var myInterval = setInterval (OnGoing , 10);
}
else {
timegraph.innerHTML="00:00:00:00";
}
}
这段代码应该是秒表。问题是clearInterval不起作用。当我第二次按下id为“start”的按钮时,控制台中的错误是:未捕获的ReferenceError:未定义myInterval。当我第二次按下该按钮时,代码秒表应该停止。
答案 0 :(得分:5)
这是因为myInterval
是在Running
下定义的。移除var
并在Running
之外定义。
答案 1 :(得分:0)
MyInterval仅存在于函数中。将var MyInterval放在函数外部。
var button1 = document.getElementById("start");
var button2 = document.getElementById("stop");
var timegraph = document.getElementById("ceas");
var time = 0;
var ResetStart = 0;
var myInterval;
function Start(){
if (ResetStart==0) {
ResetStart=1;
Running();
button1.innerHTML="Pause";
}
else {
ResetStart=0;
button1.innerHTML="Resume";
clearInterval(myInterval);
}
}
function Reset(){
time = 0;
ResetStart = 0;
button1.innerHTML="Start";
timegraph.innerHTML="00:00:00:00";
}
function OnGoing(){
time++;
var hours = Math.floor(time/100/60/60);
var minutes = Math.floor(time/100/60 % 60);
var seconds = Math.floor(time/100 % 60);
var hundreds = Math.floor(time/10 % 10);
var thousands = time % 10;
if (hours<10){
hours = "0" + hours;
}
if (minutes<10) {
minutes = "0" + minutes;
}
if (seconds<10) {
seconds = "0" + seconds;
}
timegraph.innerHTML=hours + ":" + minutes + ":" + seconds + ":" + hundreds + thousands;
}
function Running(){
if (ResetStart==1){
myInterval = setInterval (OnGoing , 10);
}
else {
timegraph.innerHTML="00:00:00:00";
}
}