Cancelling the execution of setInterval method (clearInterval)

Shows how to cancel the execution of JavaScript setInterval method using clearInterval method. Div element with id="colouredDiv" changes it's colour every 3 seconds. getRandomColour method generates random Hex colour code.
var timerID = null;
var colourDiv = document.getElementById("colouredDiv");


function colourChangerFunction() {
	colourDiv.style.backgroundColor = getRandomColour();
};

function getRandomColour() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

document.getElementById("setIntervalButton").addEventListener("click", function() {
    // Start the process of changing colours
	timerID = setInterval(colourChangerFunction, 3000);
});

document.getElementById("clearIntervalButton").addEventListener("click", function() {
    // End the process of changing colours
	clearInterval(timerID);
});

Responses

0 Replies