I am trying to write a for loop that loops through an array of colors and calls another function which uses that array to change a button color.
Currently I have an array of three colors and I want the button to change to the first color then wait then turn back to white then change to the second color then wait then turn to white then change to the third color and wait and turn to white.
Right now I have two functions that change the color of the button then use setTimeout to wait 3 seconds before calling another function that changes the button back to white.
My thought was to just run this sequence in a for loop that loops through the colors. The for loop seems to be firing but not waiting for the setTimeouts to finish from the previous iteration before continuing. I think I may need a callback but am not sure how to proceed.
html:
<body>
<button id="bigButton">Change Color</button>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</body>
CSS:
button{
background-color: white;
}
Javascript:
$("#bigButton").on('click', function(){
var a=["blue", "green", "red"];
for(var m=0; m<a.length; m++){
turnOn(a[m]);
}
});
var timerID = null;
function turnOn (inputColor) {
$("#bigButton").css("background-color", inputColor)
console.log("color changed to ", inputColor);
clearTimeout (timerID);
timerID = null;
if (timerID === null) {
timerID = setTimeout ("turnOff()", 3000);
}
}
function turnOff () {
$("#bigButton").css("background-color", "white")
console.log("color changed to white");
clearTimeout (timerID);
timerID = null;
}
codepen is here
Aucun commentaire:
Enregistrer un commentaire