I have created a setInterval function in JavaScript to switch the color of a div by applying different CSS classes. Initially, I trigger this color change by pressing a button. However, I am also trying to stop the color transition using the same button but it's not working as expected. Below is my JS code:
var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"];
var i = 0;
var buttonstate = false;
var runner;
var mainfun = function () {
if (buttonstate === false) {
buttonstate = true;
document.getElementById("changebutton").className = "btn btn-primary btn-lg active";
var runner = setInterval(function() {
document.getElementById("alertw").className = bsstyles[i];
i++;
if (i == bsstyles.length) {
i = 0;
}
},1000);
} else {
clearInterval(runner);
document.getElementById("changebutton").className = "btn btn-primary btn-lg";
buttonstate = false;
}
}
var changeButton = document.getElementById("changebutton");
changeButton.addEventListener('click',mainfun,false);
Check out the JSFiddle here