Я пытаюсь зациклить этот блок кода. Как мне это сделать? Я пытаюсь изменить цвет навсегда.
<!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)
}
@ColemanTO Это полностью заблокирует страницу.
Используйте setInterval()
для периодического запуска кода. Функция может увеличивать индекс массива.
Просто добавьте еще один changecolor()
вызов в последний (самый внутренний) setTimeout
обратный вызов.
Может быть, попробуйте что-то вроде этого.
// keep a list of all the colors you want to cycle through
const colors = [
'blue',
'red',
'lightblue',
'#800000',
'#ff0066',
'#ff6699',
'#9900cc',
'Lime',
'#000099',
'#ff9430',
];
// this function sets the color
const changeColor = (color) => {
document.body.style.backgroundColor = color;
};
// keep track of the color you are on
let colorIndex = 0;
// this function waits for an amount of milliseconds
const sleep = async (millis) => {
return new Promise((resolve) => {
setTimeout(resolve, millis);
});
};
// main function
(async () => {
// loop forever
while (true) {
// sleep for 1500 ms
await sleep(1500);
// change the color
changeColor(colors[colorIndex]);
// update the color index
colorIndex = (colorIndex + 1) % colors.length;
}
})().catch(console.error);
Функцию не обязательно помечать как асинхронную, если она просто возвращает обещание.
@gre_gor Технически это правда, но хорошей практикой является пометить функции, возвращающие обещания, как асинхронные. Я всегда следую этому правилу эслинта. Это поможет вам гарантировать, что вы всегда catch()
выполняете свои обещания.
Используйте setInterval, если вы хотите, чтобы что-то повторялось бесконечно и с постоянной скоростью.
Функция возвращает идентификатор интервала, поэтому, если вы хотите остановить его позже, вы можете вызвать clearInterval с этим идентификатором.
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>
Вы можете использовать функцию setInterval
в сочетании с массивом цветов.
const colors = ["blue", "red", "lightblue", "#800000", "#ff0066", "#ff6699", "#9900cc", "Lime", "#000099", "#ff9430"];
let index = 0;
let intervalId;
function changecolor() {
if (intervalId) {
clearInterval(intervalId);
}
intervalId = setInterval(() => {
document.body.style.backgroundColor = colors[index];
index = (index + 1) % colors.length; // This will loop back to the first color after the last one
}, 1500);
}
<h1 onclick = "changecolor()">HackerXGames</h1>
Этот код будет непрерывно перебирать цвета в массиве, меняя цвет фона каждые 1,5 секунды.
Было бы гораздо разумнее поместить все цвета в массив и циклически перебирать их в цикле.