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)
}
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.
const colors = [
'blue',
'red',
'lightblue',
'#800000',
'#ff0066',
'#ff6699',
'#9900cc',
'Lime',
'#000099',
'#ff9430',
];
let colorInterval;
let colorIndex = 0;
function startChangingBg() {
changeBackground(); // This is optional; so you don't have to wait for first interval
colorInterval = setInterval(changeBackground, 1500);
}
function stopChangingBg() {
clearInterval(colorInterval);
}
function changeBackground() {
document.body.style.backgroundColor = colors[colorIndex];
colorIndex += 1;
if (colorIndex >= colors.length) {
colorIndex = 0;
}
}
<!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>HackerXGames</h1>
<button onclick="startChangingBg()">Start changing background</button>
<button onclick="stopChangingBg()">Stop changing background</button>
</body>
</html>