THIS IS NOT A DUPLICATE!
I have a piece of JavaScript with what I call a "nested" setInterval
; one setInterval
that calls a function with another setInterval
.
What i want is when the "outer" setInterval
calls the function when the "inner" setInterval
is already running, I want the "inner" setInterval
to stop it's original interval and start again fresh.
So:
- Outer
setInterval
fires. - Outer
setInterval
calls function with innersetInterval
. - Inner
setInterval
fires.
... inner runs for a while
- Outer
setInterval
fires ... again. - Outer
setInterval
calls innersetInterval
... again - Inner
setInterval
stops it's original run. - Inner
setInterval
starts a fresh, new run.
See my example below:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div {
margin: 100px 100px;
}
</style>
<script type="text/javascript">
let alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
function start(){
var the_button = document.getElementById('the_button');
the_button.addEventListener('click', testFunction);
}
function testFunction(){
console.log("Starting ...");
if(myIntervalVal) clearInterval(myIntervalVal);
var myIntervalVal = setInterval(printAlphabet, 10000);
}
function printAlphabet(){
var i = 0;
console.log(alphabet[i]);
if(mySubInterval) clearInterval(mySubInterval);
var mySubInterval = setInterval(function(){
i++;
if(i === alphabet.length) i = 0;
console.log(alphabet[i]);
}, 1000);
}
</script>
</head>
<body onload="start();"><div><button type="button" id="the_button">click me</button></div></body>
</html>
The way I feel this should work is:
outer fires
inner prints
A
B
C
D
E
F
outer is fired again
inner stops printing
inner prints
A
B
C
D
E
F
...
Is this not possible?