[英]how to stop setInterval? clearInterval doesn't work
我想移动并停止程序。 该程序只有一个按钮。 该按钮是所有程序。 是的,这是超级简单的程序。 该程序的问题是球不会停下来。
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>
var moving = false;
var interval;
// handle the click
function handleClick() {
// if moving set moving to false, otherwise set it to true
moving = moving ? stop() : start();
}
// start the interval that calls move function and set moving to true
function start() {
moving = true;
interval = setInterval(function() {
move();
}, 500);
}
// clear the interval and set moving to false
function stop() {
moving = false;
clearInterval(interval);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.