[英]clearInterval does not clear setInterval inside function
How do I clear interval for the setInterval inside the StartGame function ?(present one is not working)如何清除 StartGame 函数内 setInterval 的间隔?(目前一个不起作用)
document.getElementById("rndletter").addEventListener("click", function StartGame() ** { setInterval(function() ** { var result0 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97); var result1 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97); var result2 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97); }, 2000); }); document.getElementById("stprndletter").addEventListener("click", function() { clearInterval(); });
<button id="rndletter">Start game</button> <button id="stprndletter">Stop game</button> <td style="text-align: center; color: blue; font-size: 150%;"> <b> <div id="result0"><br /> </div> </b></td> <td style="text-align: center; color: brown; font-size: 150%;"> <b> <div id="result1"><br /></div> </b></td> <td style="text-align: center; color: hotpink; font-size: 150%;"><b> <div id="result2"><br /></div> </b></td>
I got the answer after reading the docs, for anyone who searches the same, I have done this: (added an ID nIntervID
)我在阅读文档后得到了答案,对于任何搜索相同的人,我已经这样做了:(添加了 ID nIntervID
)
let nIntervId;
document.getElementById("rndletter").addEventListener("click", function {
nIntervId = setInterval(function() {
var result0 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97);
var result1 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97);
var result2 = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97);
document.getElementById("result0").innerText = result0;
document.getElementById("result1").innerText = result1;
document.getElementById("result2").innerText = result2;
},2000);});
document.getElementById("stprndletter").addEventListener("click", function() {
clearInterval(nIntervId);
// release our intervalID from the variable
nIntervId = null;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.