자바스크립트를 이용해 1000ms마다 배경색이 바뀌도록 만들기
setTimeout(() => {
document.body.style.backgroundColor = "red";
}, 1000);
setTimeout(() => {
document.body.style.backgroundColor = "orange";
}, 2000);
setTimeout(() => {
document.body.style.backgroundColor = "yellow";
}, 3000);
setTimeout(() => {
document.body.style.backgroundColor = "green";
}, 4000);
setTimeout(() => {
document.body.style.backgroundColor = "blue";
}, 5000);
setTimeout(() => {
document.body.style.backgroundColor = "indigo";
}, 6000);
setTimeout(() => {
document.body.style.backgroundColor = "purple";
}, 7000);
setTimeout(() => {
document.body.style.backgroundColor = "red";
setTimeout(() => {
document.body.style.backgroundColor = "orange";
setTimeout(() => {
document.body.style.backgroundColor = "yellow";
setTimeout(() => {
document.body.style.backgroundColor = "green";
setTimeout(() => {
document.body.style.backgroundColor = "blue";
setTimeout(() => {
document.body.style.backgroundColor = "indigo";
setTimeout(() => {
document.body.style.backgroundColor = "purple";
}, 1000);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
const changBgColor = (color, delay, NextColor) => {
setTimeout(() => {
document.body.style.backgroundColor = color;
NextColor && NextColor();
}, delay);
};
changBgColor("red", 1000, () => {
changBgColor("orange", 1000, () => {
changBgColor("yellow", 1000, () => {
changBgColor("green", 1000, () => {
changBgColor("blue", 1000, () => {
changBgColor("indigo", 1000, () => {
changBgColor("purple", 1000, () => {});
});
});
});
});
});
});
const changeColor = (color, delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
document.body.style.backgroundColor = color;
resolve();
}, delay);
});
};
changeColor("red", 1000)
.then(() => changeColor("orange", 1000))
.then(() => changeColor("yellow", 1000))
.then(() => changeColor("green", 1000))
.then(() => changeColor("blue", 1000))
.then(() => changeColor("indigo", 1000))
.then(() => changeColor("purple", 1000));
const changeColor = (color, delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
document.body.style.backgroundColor = color;
resolve();
}, delay);
});
};
const changeBG = async () => {
try {
await changeColor("red", 1000);
await changeColor("orange", 1000);
await changeColor("yellow", 1000);
await changeColor("green", 1000);
await changeColor("blue", 1000);
await changeColor("indigo", 1000);
await changeColor("purple", 1000);
return console.log("END");
} catch (error) {
console.log(error);
}
};
changeBG();