first of all, Welcome to StackOverflow
Your code works fine, but remember that you are using setTimout
, so even if you call stopInterval()
, the code inside the timeout will fire once more
to prevent it, you could do this
- start the interval with
0
- when
clearInterval()
set the interval to 0
once again
- now, inside the
setTimeout
function, only run the code if interval > 0
does it makes sense?
here's a simple example in JsBIN and well with StackOverflow Code:
var pre = document.querySelector("pre")
var interval = 0;
function startInterval() {
pre.innerHTML += 'START called\n';
interval = setInterval(function() {
pre.innerHTML += 'type code\n';
setTimeout(function() {
if (interval > 0 ) {
// only if the interval is not cleared
pre.innerHTML += 'other code\n';
}
}, 1000);
}, 2000);
}
function stopInterval() {
pre.innerHTML += 'STOP called\n';
clearInterval(interval);
interval = 0;
}
document
.querySelector("#btnStart")
.addEventListener("click", startInterval);
document
.querySelector("#btnStop")
.addEventListener("click", stopInterval);
<button id="btnStart">START</button> <button id="btnStop">STOP</button>
<hr/>
<pre></pre>