如何停止setInterval?清除间隔不起作用
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);
}
我想制作移动和停止程序。 这个程序只有一个按钮。该按钮是所有程序。 是的,这是超级简单的程序。 程序的问题是球没有停下来
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);
}