I am trying to change the background color of my HTML page, every 200 milliseconds using setInterval in the event of a click on the button id = 'button4'. And I want the changing of background color to stop when the user clicks on the same button again.
The code for setInterval is executed when assigned to var x whereas I want to execute it when a condition is satisfied inside the 'goCrazy' function when it is called. How can that be done?
The clearInterval is working fine and the changing of colors is stopped.
Below is my code.
var x = setInterval(() => {
const rndInt1 = randomIntFromInterval(0, 255);
const rndInt2 = randomIntFromInterval(0, 255);
const rndInt3 = randomIntFromInterval(0, 255);
document.body.style.backgroundColor = `rgb(${rndInt1}, ${rndInt2}, ${rndInt3})`;
}, 200);
function goCrazy() {
if (document.getElementById('button4').innerText == 'Go Crazy') {
document.getElementById('button4').innerText = 'stop';
x;
}
else {
clearInterval(x);
document.getElementById('button4').innerText = 'Go Crazy';
}
}
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
You can extract the code inside setInterval
into a named function, and call setInterval
or clearInterval
within goCrazy
.
var x;
function goCrazy(){
if (document.getElementById('button4').innerText == 'Go Crazy') {
document.getElementById('button4').innerText = 'stop';
x = setInterval(changeBackground, 200);
}
else {
document.getElementById('button4').innerText = 'Go Crazy';
if (x) clearInterval(x);
}
}
function changeBackground() {
const rndInt1 = randomIntFromInterval(0, 255);
const rndInt2 = randomIntFromInterval(0, 255);
const rndInt3 = randomIntFromInterval(0, 255);
document.body.style.backgroundColor = `rgb(${rndInt1}, ${rndInt2}, ${rndInt3})`;
}
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}