kthornbloom kthornbloom - 1 month ago 16
jQuery Question

clearInterval won't clear the interval

This is pretty simple, you click a button to start a "setInterval", and click another button to stop it. The stop button does not work.

I realize there are lots of similar questions, but I thought I had already set things up like the answers stated to. How do I correctly clear the interval here?

Code:



// declare globally
var runslides;

// set up play function
function startPlaying(){
// set interval
var runslides = setInterval(slides, 1000);
}

// function for set interval to use
function slides(){
$('body').append('<div>Function Ran</div>');
}

// start the interval
$(document.body).on('click', '#start' ,function(event){
startPlaying();
});

// stop the interval
$(document.body).on('click', '#stop' ,function(event){
clearInterval(runslides);
});

html, body {
font-family:sans-serif;
font-size:12px;
background:#222;
}

a:link, a:visited {
background:#fff;
text-decoration:none;
padding:5px;
display:inline-block;
}

div {
display:inline-block;
background:#ccc;
padding:5px;
margin:5px 5px 0 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" id="start">Click To Start</a>
<a href="#" id="stop">Click To Stop</a>
<br>




Answer

You are re-declaring var runslides = setInterval(slides, 1000); locally just do:

runslides = setInterval(slides, 1000);