簡體   English   中英

javascript在while循環中使用setInterval不起作用

[英]javascript Using setInterval inside a while loop doesn't work

我正在開發一個小游戲,你必須點擊正確的目標。 我有一組不同 id 的 div,編號從 1 到 9。每 3 秒目標就會改變一次。 為了選擇目標,我做了一個隨機選擇目標的函數,直到用戶擊中正確的目標。 這是我現在所做的代碼:

let game;
let victory = false;
let target;


const win = () => {
    victory = true;
    return alert('Has ganado');
}


const setTarget = () => {

    console.log("funcion setTarget");
    target = Math.floor(Math.random() * 9) + 1;

    // Añadimos la classe red
    document.getElementById(target).classList.add("target");

    // Al target actual le ponemos un eventlistener
    document.getElementById(target).addEventListener('click', win);

    return target;

}



// Al target anterior hay que eliminarle la classe red y quitarle el eventlistener
const removeTarget = () => {


    // Eliminamos la classe red
    document.getElementById(target).classList.remove("target");

    // Al target anterior le borro la classe "target"
    document.getElementById(target).removeEventListener('click', win);

    return target;

}


const startGame = () => {


    while (victory) {

        console.log("Entramos en el while");

        setTarget(); // Aplicamos estilo al target y le aplicamos event listener

        setTimeout(() => removeTarget, 30000); // Esperamos 3 segundos y eliminamos el target

    }

    return true;

}



// Ejecuta la función que hace todo el juego
startGame();

在函數 startGame 中,我需要執行函數 setTarget() 然后等待 3 秒再執行 removeTarget 這應該發生,直到用戶點擊正確的元素。 當用戶單擊正確的元素時,勝利將變為真並且循環退出。 現在,當我加載頁面時,它根本不需要等待,而且速度如此之快,以至於我看不到 div 的顏色變化。

這是 if 的 html 可能有用:

<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div>
            <div id="1"></div>
            <div id="2"></div>
            <div id="3"></div>
          </div>
           
          <div>
            <div id="4"></div>
            <div id="5"></div>
            <div id="6"></div>
          </div>
           
          <div>
            <div id="7"></div>
            <div id="8"></div>
            <div id="9"></div>
          </div>


        <script src="script.js"></script>
    </body>
</html>

和 CSS:

div>div {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    display: inline-block;
    border-radius: 50px;
  }
 
  .target {
    background-color: red;
  }

代碼更改:

不要使用while ,這就是間隔的用途:

const startGame = () => {
    setTarget();
    window.my_interval = setInterval(adjustTarget, 30*1000);
}

然后一旦用戶獲勝,清除間隔:

const win = () => {
    clearInterval(window.my_interval);
    removeTarget();
    alert('Has ganado');
}

您將需要一個重置目標的臨時方法。 因此,聲明另一個為您執行此操作的函數,例如:

function adjustTarget(){
    removeTarget();
    setTarget();
}

學習內容總結:

  • 第一victoryfalse所以你的while循環永遠不會進入。
  • 第二:即使victory是真的,你也會鎖定你的運行時並得到Maximum call stack size exceeded while循環不會在setTimeout()上等待,因此它會設置數千/數百萬/數十億的超時。
  • 第三:您不需要聲明一個匿名函數,然后返回對removeTarget的引用。 只需將removeTarget函數引用直接傳遞給setTimeout()即可。
  • 第四:在您調用startGame()時您的victory startGame()將始終為false 所以你在開始游戲時不需要檢查它。
  • 第五:考慮將所有代碼放在一個class ,以便於變量、狀態和范圍管理。
  • 第六:你甚至不需要victory的變量,當用戶點擊“獲勝”目標時它是隱含的。
  • 第七:您沒有使用任何方法的return值。 因此,您甚至不應該使用 return 語句。

看這個,我更新了幾行JavaScript,其余保持不變

const win = () => {
victory = true;
clearInterval(startit);
return alert('Has ganado');
}

const startGame = () => {
    console.log("Entramos en el while");
    removeTarget(); // Esperamos 3 segundos y eliminamos el target
    setTarget(); // Aplicamos estilo al target y le aplicamos event listener
}

var startit = setInterval(startGame, 3000);
enter code here

暫無
暫無

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

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