Essentially, I am trying to create a webpage that has 2 buttons; one will cause the screen to flash randomly, and the other will cause it to slowly change colours. I want to be able to switch between these two (if you press the first button it starts flashing and then if you press the second button it slowly changes without any kind of cancel button).
The buttons each call a function which sets the 'running' variable of the other function to false and it's own 'running' variable to true. It then calls a recursive function (recursive in that it just calls itself over and over). These recursive functions only execute their code when their 'running' variable is true.
If you run the snippet you can see that the program is very inconsistent (you may need to play with it for a bit to see the issue since it sometimes seems to work). Sometimes it refuses to change function and other times the two functions seem to both be active and they both try to execute (it almost looks as if they are fighting for control). I don't understand how this is happening since, I believe, only one of the 'running' variables can be true at any time.
var runningDisco = false;
var runningColours = false;
function startColours() {
if (runningDisco == true); //Is disco running?
{
runningDisco = false; //If yes, stop it
}
runningColours = true; //Indicate we are running
window.setTimeout(Colours, 100, 0); //Run
}
function startDisco() {
if (runningColours == true); {
runningColours = false;
}
runningDisco = true;
window.setTimeout(Disco, 100);
}
function Disco() {
if (runningDisco == true); {
hex = "#";
for (discoCount = 0; discoCount < 6; discoCount++) {
hex = hex.concat((Math.floor(Math.random() * 17)).toString(16));
}
document.body.style.background = hex;
window.setTimeout(Disco, 10);
}
}
function Colours(colourCount) {
if (runningColours == true); {
if (colourCount > 359) {
colourCount -= 359;
}
document.body.style.background = "hsl(" + colourCount + ", 50%, 50%)";
window.setTimeout(Colours, 10, colourCount + 1);
}
}
input {
font-family: 'Roboto', sans-serif;
text-align: center;
background-color: #dd1021;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<input id="clickMe" type="button" value="Start Disco" onclick="startDisco();" />
<input id="clickMe" type="button" value="Start Colours" onclick="startColours();" />