https://codepen.io/fodi91/pen/ExNqGpY
First I click the random background every 4 seconds button, then I click the random background onclick button, but the interval doesn’t stop. Why? How can I solve this?
let onClick = document.getElementById('generate'); onClick.addEventListener('click', generator); let onClick2 = document.getElementById('generate2'); onClick2.addEventListener('click', generator2); function generator2() { let r = Math.floor(Math.random() * 256); let g = Math.floor(Math.random() * 256); let b = Math.floor(Math.random() * 256); let background = document.getElementById('random'); background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')'; myInterval = setInterval(generator2, 2000); } function generator() { let r = Math.floor(Math.random() * 256); let g = Math.floor(Math.random() * 256); let b = Math.floor(Math.random() * 256); let background = document.getElementById('random'); background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')'; clearInterval(myInterval); }
Advertisement
Answer
There are a couple of issues with your code.
Firstly, you need to declare your myInterval variable outside of the generator2()
function.
The second issue is that your interval function is calling itself creating a recursive loop. Separate your callback which sets the interval from the code you want to execute on each interval.
let myInterval; let onClick = document.getElementById('generate'); . . . onClick2.addEventListener('click', secondClickHandler); function secondClickHandler() { myInterval = setInterval(generator2, 2000); } function generator2() { let r = Math.floor(Math.random() * 256); let g = Math.floor(Math.random() * 256); let b = Math.floor(Math.random() * 256); let background = document.getElementById('random'); background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')'; }
With that in mind, here’s how I’d approach it:
const generate1Button = document.getElementById('generate'); const generate2Button = document.getElementById('generate2'); const randomBackground = document.getElementById('random'); let backgroundInterval; generate1Button.addEventListener('click', () => { clearInterval(backgroundInterval); setRandomBackgroundColor(); }) generate2Button.addEventListener('click', () => { setRandomBackgroundColor(); backgroundInterval = setInterval(setRandomBackgroundColor, 2000); }) function setRandomBackgroundColor() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); randomBackground.style.backgroundColor = `rgb(${r}, ${g}, ${b})`; }