简体   繁体   中英

how to stop setInterval? clearInterval doesn't work

I want to make moving and stop program. This program has just one button. The button is all of program. Yeah, It is super simple program. The program's problem is that the ball doesn't stop.

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"/>

The thing that i want is When i click Shoot button, the ball should move, click again, stop. Excuting my code, click once, the ball moves correctly. click again, It doesn't stop. It's my problem. How to stop the ball?

The problem is that you're resetting tev every time you hit the button. Save that value outside of the function and it'll work just fine.

 // 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM