Superman2971
Superman2971

Reputation: 1535

Stop a setInterval function

I'm trying to make this setInterval function stop when the button switches to "STOP" and is clicked. The word START is changing to STOP and vice-versa, but the random BG color changes won't stop and instead compound.

$(document).ready(function(){
function randomColor(){
    return "#" + Math.random().toString(16).slice(2,8);
};

$("button").click(function(){
    var $go = $("button").text();
    if ($go === "START"){
        setInterval(function Colors(){
            $("body").css("background-color", randomColor());
            }, 300);
        $("button").text("STOP");
    }
    else {
        //Tried clearInterval and doing a new $("body").css("background-color","white")
        $("button").text("START");
    };
});
});

Please let me know if a link to the site or additional info would be helpful. Thank you!

Upvotes: 0

Views: 76

Answers (1)

Oriol
Oriol

Reputation: 288020

You must save the value returned by setInterval in a variable, and pass it to clearInterval when you want to stop:

var timer;
$("button").click(function(){
    var $go = $("button").text();
    if ($go === "START"){
        timer = setInterval(function Colors(){
            $("body").css("background-color", randomColor());
            }, 300);
        $("button").text("STOP");
    }
    else {
        clearInterval(timer);
        $("button").text("START");
    };
});

Upvotes: 2

Related Questions