gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:58:40 26 4
gpt4 key购买 nike

我永远无法在两种颜色的 body 之间循环。它只循环一次。
我使用“回车”键触发循环,使用“空格”键停止循环。

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方法,仅使用函数属性 countred 之间切换和 blue , 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;
    }
    });

    关于javascript - 如何在纯 JavaScript 中在两种颜色之间循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63662998/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com