如何在纯JavaScript中在两种颜色之间循环



我永远无法在身体的两种颜色之间循环。它只循环一次。

我使用"回车"键来触发循环,使用"空格"键来停止循环。

const red= () => {
document.body.style.backgroundColor = "red";
}
const blue= () => {
document.body.style.backgroundColor = "blue"; 
}

const both =  () => {
setTimeout(() => red(), 1000);
setTimeout(() => blue(), 2000);
}
document.body.addEventListener("keydown", function() {
if (event.keyCode == 13) {
setInterval(both(), 3000);
}
if (event.keyCode == 32) {
clearInterval(both());
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Looping Colors</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="script.js"></script>
</body>
</html>

您当前在代码中犯的错误是:

  • 调用函数redblue,并将该值指定为超时的回调(未定义(
  • both没有返回对超时的引用
  • setTimeout只运行一次
  • clearInterval不能像您所认为的那样对函数引用起作用,但它的结果是setInterval
  • setTimeout可能不太合适,您可以更容易地使用setInterval

在下面的代码中,我添加了一个额外的toggle方法,它只使用函数属性countredblue之间切换,both返回setInterval的值并将其分配给函数属性interval以跟踪该间隔,然后清除该

const red= () => {
document.body.style.backgroundColor = "red";
}
const blue= () => {
document.body.style.backgroundColor = "blue"; 
}
const toggle = () => {
// when toggle.count doesn't exist, use 0 and increase with 1
toggle.count = (toggle.count || 0) + 1;
// when even -> call red() otherwise call blue()
// you could also verify here what is the backgroundColor
toggle.count % 2 === 0 ? red() : blue();
}
// returns the result of `setInterval` so the interval can be cleared
const both = () => setInterval( toggle, 1000 );

document.body.addEventListener("keydown", function keyhandler() {
if (event.keyCode == 13 && !keyhandler.interval) {
// keep the result of both (setInterval) as reference to the interval
// mind you, pressing enter twice would leave 1 interval running indefinitely
// unless you check if interval has a value
keyhandler.interval = both();
}
if (event.keyCode == 32) {
clearInterval( keyhandler.interval );
// delete the interval property so you can restart the loop afterwards
delete keyhandler.interval;
}
});

您的第一个问题是setTimeoutsetInterval接受函数的输入,而不是函数的结果。你应该写setTimeout(red, 1000)而不是setTimeout(red(), 1000)

第二个问题是clearInterval没有函数。相反,它采用setInterval函数的返回值:

var int = setInterval(both, 3000);
clearInterval(int);

完整更新代码:

const red= () => {
document.body.style.backgroundColor = "red";
}
const blue= () => {
document.body.style.backgroundColor = "blue"; 
}
const both =  () => {
setTimeout(red, 1000);
setTimeout(blue, 2000);
}
document.body.addEventListener("keydown", () => {
let bothInt;
if (event.keyCode == 13) {
bothInt = setInterval(both, 3000);
bothIntClear = false;
}
else if (event.keyCode == 32) {
clearInterval(bothInt);
}
});

请记住,颜色可能需要一段时间才能停止切换,因为函数仍在事件队列中。

最新更新