我想要制作移动和停止程序。 这个程序只有一个按钮。该按钮是程序的全部。 是的,这是一个 super 简单的程序。 该程序的问题是球没有停止。
function onSubmit() {
var tev = setInterval(move, 500);
if (animate == false) {
setInterval(move, 500);
animate = true;
} else {
clearInterval(tev);
animate = false;
}
}
<input type="button" onclick="onSubmit();" value="Shoot"/>
我想要的是当我单击“射击”按钮时,球应该移动, 再次点击,停止。 执行我的代码,点击一次,球正确移动。再按一下,就不会停止。这是我的问题。 如何让球停下来?
最佳答案
问题是每次按下按钮时都会重置 tev
。将该值保存在函数之外,它就可以正常工作。
// Save outside of the function so it will keep it's value
var timeoutID;
document.getElementById('clickMe').addEventListener('click', function() {
// Notice that I'm not re-assigning timeoutID
// every time I click the button
if (timeoutID) {
console.log('Stopped');
clearInterval(timeoutID);
// Clear out the ID value so we're ready to start again
timeoutID = null;
} else {
timeoutID = setInterval(function() {
console.log('Rolling...');
}, 500);
}
});
<button id="clickMe">Start/Stop</button>
关于javascript - 如何停止setInterval?清除间隔不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43459107/