I have some code where I have a timer. Every 3 seconds the background changes colors, and when you hover the stop button, the color changer pauses, I have an onclick event that i am using in junction with the mouseout event but the mouseout event cancels out my onclick event. What can I do so that the onclic event works still after I move the mouse from the stop button?
Code: jsfiddle
<script>
var colors = new Array();
colors[0] = "green";
colors[1] = "blue";
colors[2] = "gray";
var i = 0;
var timer;
function changeOfPlans() {
timer = setInterval("colorChange()", 3000);
}
function colorChange() {
document.getElementById("one").style.backgroundColor = colors[i];
document.getElementById("two").style.backgroundColor = colors[i];
i++;
if (i == 3 || i > 3) {
//start over by setting i to 0
i = 0;
}
}
function stop() {
clearTimeout(timer);
}
</script>
You need to update the on click action so that it sets a variable. Then have the mouse out first check whether that variable is set before restarting the color changing. Demo.
I modified your JavaScript like so:
Then I updated your onclick to call
fullstop()instead of juststop(). Since I left the otherstop()function the same, the hover-to-stop-move-away-to-restart functionality still works as you had it originally. All of the other JavaScript remains the same.There are other ways of doing this — enhzflep suggests a good one in the comments — but this is the simplest.