I am trying to loop this block of code. How do I do that? I am trying to change the color forever.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="styles.css" />
<script defer src="script.js"></script>
</head>
<body>
<h1 onclick="changecolor()">HackerXGames</h1>
</body>
</html>
function changecolor(){
setTimeout(() => {
document.body.style.backgroundColor = "blue";
setTimeout(() => {
document.body.style.backgroundColor = "red";
setTimeout(() => {
document.body.style.backgroundColor = "lightblue";
setTimeout(() => {
document.body.style.backgroundColor = "#800000";
setTimeout(() => {
document.body.style.backgroundColor = "#ff0066";
setTimeout(() => {
document.body.style.backgroundColor = "#ff6699";
setTimeout(() => {
document.body.style.backgroundColor = "#9900cc";
setTimeout(() => {
document.body.style.backgroundColor = "Lime";
setTimeout(() => {
document.body.style.backgroundColor = "#000099";
setTimeout(() => {
document.body.style.backgroundColor = "#ff9430";
},1500)
},1500)
},1500)
},1500)
},1500)
},1500)
},1500)
},1500)
},1500)
},2500)
}
2
Answers
Maybe try something like this.
Use setInterval if you want something to loop endlessly at a continuous rate.
The function returns an ID for the interval, so if you want to stop it at a later time, you can call clearInterval with that ID.