Home > front end >  Why does setInterval only seem to work once in the DOM?
Why does setInterval only seem to work once in the DOM?

Time:11-30

I'm trying to play with the setInterval method and I'm just wondering what I have done wrong here. If I program it to return an alert, no problem - it appears at every interval as expected. However, I want my background color to change every few seconds and it's not happening. The color is altered once and that's all the fun I get.

enter image description here

I've had a look at similar posts on Stack Overflow and played around, but to no avail. Any suggestions much appreciated. Thanks million!

CodePudding user response:

setInterval function is in fact running every 2 seconds, but choice1 variable it's being randomized once. You have to generate new values to choice1 inside setInverval callback to get the result you want. An example:

function changeColor() {
   choice1 = /*Your random function here*/
   document.body.style.backgroundColor = choice1;
}

CodePudding user response:

I think the setInterval works properly. The issue is you don't get a new choice1.

You can try this

 document.body.style.backgroundColor = oneArray[Math.floor(Math.random() * oneArray.length)]
  • Related