0
Dom - Changing
Hello guys can i repeat my function? function body(){ var g = document.getElementsByTagName("body"); for(var x=0; x<g.length;x++){ g[x].style.backgroundColor = '#33EA73'; } } setTimeout(body, 1000);
2 Respostas
+ 15
you need a random number generator + setInterval for that check my code modify it to your use case.
https://code.sololearn.com/W52kSFk6QTE3/?ref=app#html
+ 5
/*
Your function is only delayed for 1s only once, as setTimeout is called only out of the 'body' function... and anyway, even if it was repeating, color doesn't change so you will never see any visual repetition ^^
To make it repeating, you have mostly two solutions:
*/
function body() {
/* code to be repeated */
setTimeout(body,1000);
}
body(); // call it a first time to initiate the infinite loop
// or:
function body() {
/* code to be repeated */
}
setInterval(body,1000);
/*
To make some not random color change:
*/
var colors = ['FF0000','FFFF00','00FF00','00FFFF','0000FF','FF00FF'];
var index = 0;
var g = document.getElementsByTagName("body")[0]; // only once <body> element can be found, and avoiding getElement at each time function is called
function body {
g.style.backgroundColor = '#'+index;
index=(index+1)%colors.length;
}
setInterval(body, 1000);
// or, more concise:
var colors = ['FF0000','FFFF00','00FF00','00FFFF','0000FF','FF00FF'];
var index = 0;
var g = document.getElementsByTagName("body")[0];
setInterval(() => { g.style.backgroundColor = '#'+index++; index %= colors.length }, 1000);