簡體   English   中英

如何在純 JavaScript 中的兩個 colors 之間循環?

[英]How to Loop between two colors in pure 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>

您當前在代碼中犯的錯誤是:

  • 您調用 function redblue並將該值指定為超時的回調(未定義)
  • both都沒有返回對超時的引用
  • setTimeout運行一次
  • clearInterval不適用於您認為的 function 參考,但結果為setInterval
  • setTimeout可能不太合適,您可以更輕松地使用setInterval

在下面的代碼中,我添加了一個額外的toggle方法,它只使用 function 屬性countredblue之間切換, both返回setInterval的值並將其分配給 function 屬性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接受 function 的輸入而不是 function 的結果。而不是setTimeout(red(), 1000)你會寫setTimeout(red, 1000)

您的第二個問題是clearInterval不采用 function。相反,它采用setInterval function 的返回值:

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);
 }
});

請記住,colors 可能需要一段時間才能停止切換,因為這些函數仍在事件隊列中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM