Javascript 无法以清除间隔停止
尽管我在两个设置间隔中使用了全局变量,但计时器从不停止计数,有时它会无缘无故地倒数。如果您需要更多的代码或代码需要更多的解释,请评论我。在代码的最后,我有了ClearInterval函数。clearInt1和clearInt2也是全局变量。谢谢Javascript 无法以清除间隔停止,javascript,date,timer,setinterval,clearinterval,Javascript,Date,Timer,Setinterval,Clearinterval,尽管我在两个设置间隔中使用了全局变量,但计时器从不停止计数,有时它会无缘无故地倒数。如果您需要更多的代码或代码需要更多的解释,请评论我。在代码的最后,我有了ClearInterval函数。clearInt1和clearInt2也是全局变量。谢谢 var buttonS = document.createElement("button"); buttonS.id = "score"; buttonS.value = "score";
var buttonS = document.createElement("button");
buttonS.id = "score";
buttonS.value = "score";
buttonS.textContent = "score";
document.body.appendChild(buttonS);
appendBreak();
var buttonT = document.createElement("button");
buttonT.id = "Time";
buttonT.value = "Time";
buttonT.textContent = "Time";
document.body.appendChild(buttonT);
clearInt1=setInterval(function(){updateScore()}, 5);
clearInt2=setInterval(function(){updateTime()},5);
function updateScore(){
document.getElementById('score').innerHTML = "Score = Right moves: "+rightMoves+", Wrong moves: "+wrongMoves;
}
function updateTime(){
var theNow=new Date();
var minN=theNow.getMinutes();
var secN=theNow.getSeconds();
var minS=startDate.getMinutes();
var secS=startDate.getSeconds();
var min = minN-minS;
var sec = secN- secS;
document.getElementById('Time').innerHTML = "Time elapsed = Minutes: "+min+", Seconds: "+sec;
}
function onCl1 (id, value) {
clearInt2=setInterval(function(){updateTime()},5);
console.log(id, value);
clicks++;
if(clicks == 2) {
if(id != previousId && value == previousValue) {
clicks =0;
rightMoves=rightMoves+1;
clearInt1=setInterval(function(){updateScore()}, 500);
alert("yeah");
var obx = document.getElementById(id);
var oby = document.getElementById(previousId);
obx.disabled=true;
oby.disabled=true;
if(rightMoves==2){
var stopD= new Date();
clearInterval(clearInt1);
var minS= startDate.getMinutes();
var secS= startDate.getSeconds();
var minE= stopD.getMinutes();
var secE = stopD.getSeconds();
var min1 = minE- minS;
var sec1 = secE-secS;
clearIntervals();
alert("Congratulations! Right moves "+rightMoves+" , Wrong moves "+wrongMoves+" Time elapsed : Minutes "+min1+" Seconds "+sec1);
clearIntervals();
appendBreak();
var buttonR = document.createElement("button");
buttonR.id = "R";
buttonR.value = "Play again!";
buttonR.textContent = "Play again!";
document.body.appendChild(buttonR);
buttonR.addEventListener("click",function(){location.reload()});
}
}else{
clicks =0;
wrongMoves=wrongMoves+1;
clearInt1=setInterval(function(){updateScore()}, 500);
alert("bad move! Think again!");
}
}
else {
previousId = id;
previousValue = value;
}
function clearIntervals(){
clearInterval(clearInt1);
clearInterval(clearInt2);
}
}
你在多个地方开始这些间歇。我怀疑你给他们打了好几次电话/有时是你想不到的。Clearinterval是有效的,因此问题在于code.hmmm中的逻辑。您必须是正确的。为了避免这种情况,你建议把它们放在哪里?thanks@Maf28我认为,如果您在创建之前为线路上的每个循环单独使用clearInterval,则出现故障的可能性最小,例如clearIntervalclearint1;然后clearInt1=setIntervalfunction{},500;它正在工作,谢谢: