Currently, I am developing a test page that consists of buttons triggering various scripts. One of the functionalities I am trying to implement is changing the background color every second for 5 seconds, cycling through a total of 5 different colors. Despite researching and learning about setInterval
and setTimeout
, I still find it challenging to grasp.
The desired sequence:
x
wait 1 sec
y
wait 1 sec
z
wait 1 sec
etc...
I initially attempted to incorporate all these changes within one function but encountered complexity in referencing a function within setTimeout(function, 500)
.
Therefore, I resorted to creating individual functions for each color change, as shown below. Subsequently, I created a master function named disco()
to invoke each background alteration.
To be frank, I am quite confused at this point. The provided code should illustrate my attempts, but unfortunately, the desired outcome was not achieved, leading me to a dead-end.
I would deeply appreciate an explanation or guidance on how to accomplish this task effectively. Thank you!
function disco() {
setTimeout(aquaman, 500);
setTimeout(pinkman, 500);
setTimeout(blueman, 500);
setTimeout(redman, 500);
setTimeout(brownman, 500);
}
function aquaman() {
document.body.style.backgroundColor = "aqua";
}
function brownman() {
document.body.style.backgroundColor = "brown";
}
function redman() {
document.body.style.backgroundColor = "red";
}
function pinkman() {
document.body.style.backgroundColor = "pink";
}
function blueman() {
document.body.style.backgroundColor = "blue";
}