简体   繁体   English

如何使循环在事件发生之前不继续?

[英]How to make loop not to continue until an event happens?

I am writing a function of a game:我正在写一个 function 的游戏:

function Game(){
    while(true){

        ***

        for(var i = 0; i < level; i++){
            var color;
            $(".btn").on("click", function(event) {
                ButtonClickResponse(this.id);
                color = this.id;
            });
            if(colorsOrder[i] != color){
                GameOver();
                return;
            }
        }

        ***

    }
    
}

the "if statement" in the loop of function runs and increments "i" immediately many times when loop is started and doesnt wait for an above event to finish. function 循环中的“if 语句”在循环开始时运行并立即递增“i”多次,并且不等待上述事件完成。

I searched for solving with "async await" and "promise" in google and stackoverflow, but didn't really understand how it worked so couldn't implemet it in my code.我在 google 和 stackoverflow 中搜索了使用“async await”和“promise”来解决问题,但并不真正理解它是如何工作的,所以无法在我的代码中实现它。

This should work, although I didn't test it and you do things not in javascript way这应该有效,虽然我没有测试它并且你做事不是 javascript 方式

async function Game() {
  while (true) {
    var level = 1;
    $("#level-title").text("Level " + level);
    var colorsOrder = [];
    var randColor = GenerateRandomSquareColor();
    colorsOrder.push(randColor);
    ButtonClickResponse(randColor);

    for (var i = 0; i < level; i++) {
      var color;

      // await for the click event
      const event = await waitForClick($(".btn"));
      // do stuff with the result
      ButtonClickResponse(event.target.id);
      color = event.target.id;

      if (colorsOrder[i] != color) {
        GameOver();
        return;
      }

      level++;
    }
  }
}

function waitForClick(element) {
  // create new promise
  return new Promise((resolve) => {
    const handler = function (event) {
      // when button is clicked remove listener
      element.off("click", handler);
      // and resolve the promise
      resolve(event);
    };
    // listen for click
    element.on("click", handler);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM