0

I am playing around with bookmark snippets and I am trying to make a loop that changes the background color rapidly. This is my code:

var one;
funtion two() {
  document.body.style.backgroundColor = "#" + Math.floor(Math.random() * 1000);
  setTimeout(two, 1);
}
void 0

I am not very good at coding, so I am trying to make it very simple.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Komali
  • 77
  • 10

3 Answers3

1

The best solution is to integrate the body's color change method into a setInterval function that will trigger at each desired interval.

window.setInterval(function(){
   document.body.style.background = '#'+Math.floor(Math.random()*16777215).toString(16);

}, 1);

Ps :The interval is in millisecond

Léo R.
  • 2,620
  • 1
  • 10
  • 22
1

You can do what you want with this code snippet:

function randomBackground() {
  var red = Math.floor(Math.random() * 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);
  document.body.style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
}
setInterval(randomBackground, 1);
Sanyika
  • 26
  • 3
1

I submitted this snippet as an edit also, but I'm not entirely sure how those work. So I'm also submitting it as answer also. I've accomplished what you want by editing your original code as little as possible. Here's what I changed.

  1. function was spelled funtion
  2. You needed to use setInterval instead of setTimeout
  3. You needed to then initiate that setInterval from outside the function two() you are calling it from: `setInterval(two, 1)
  4. As others have mentioned, you can change the number 1 at the end to any other number of milliseconds you want it to hold each color for.

var one;
function two() {
  document.body.style.backgroundColor = "#" + Math.floor(Math.random() * 1000);
};
setInterval(two, 1);

Cheers!

JSONaLeo
  • 416
  • 6
  • 11