Recursive setTimeout

Shows how to use setTimeout method as setInterval method. In this example colourChangerFunction method is called every 3 seconds with setTimeout instead of setInterval. Div element with id="colouredDiv" changes it's colour every 3 seconds. getRandomColour method generates random Hex colour code.
var timeoutTimerId = null;
var colourDiv = document.getElementById("colouredDiv");

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

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

document.getElementById("setCycleTimeoutButton").addEventListener("click", function() {
    // Start the process of changing colours
	timeoutTimerId = setTimeout(function tick() {
		colourChangerFunction();
		timeoutTimerId = setTimeout(tick, 3000);
	}, 3000);
});

document.getElementById("clearCycleTimeoutButton").addEventListener("click", function() {
    // End the process of changing colours
	clearTimeout(timeoutTimerId);
});

Responses

0 Replies