1

So my main goal is to randomize background every 1 second after clicking button. The problem is I'm getting random RGB every second as my console outputs it, but the background changes only after the last iteration.

function random_background(){
var i;
for(i = 0; i < 3; i++){
    let red = Math.floor(Math.random() * 256);
    let green = Math.floor(Math.random() * 256);
    let blue = Math.floor(Math.random() * 256);
    let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
    console.log(randomcolor);
    document.body.style.background = randomcolor;
    sleep(1000);
}
}
sijicc
  • 11
  • 1

3 Answers3

1

Javascript doesn't have any sleep method. To call a function after x times repeatedly you can use setInterval

function random_background() {
   let red = Math.floor(Math.random() * 256);
   let green = Math.floor(Math.random() * 256);
   let blue = Math.floor(Math.random() * 256);
   let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
   document.body.style.background = randomcolor;
}
setInterval(random_background, 1000);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Probably dont really want the loop in there though – Patrick Evans Nov 20 '19 at 19:16
  • Thank you, It worked. Although why didn't defining function sleep didn't work? ``` function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } ``` – sijicc Nov 20 '19 at 19:19
  • That is just a loop, it doesn't allow for the ui update nor any other code to run while it is running. Javascript is single threaded which means when it is busy so is the ui – Patrick Evans Nov 20 '19 at 19:22
  • Didn't know that. I guess thats the problem of learning without preparation. Thanks again! :) – sijicc Nov 20 '19 at 19:25
0

Use setinterval instead of sleep to give the browser a chance to do other things. Eg updating the display

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

There is no sleep function in Javascript. You should use setInterval to run a function until the interval is clear and at an interval of 1 second.

Also, i don't see why you need a for loop here so i've removed it.

let interval = setInterval(() => {
  let red = Math.floor(Math.random() * 256);
  let green = Math.floor(Math.random() * 256);
  let blue = Math.floor(Math.random() * 256);
  let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
  document.body.style.background = randomcolor;
}, 1000);
Nicolas
  • 8,077
  • 4
  • 21
  • 51