如何使循环不继续直到事件发生?

huangapple go评论96阅读模式
英文:

How to make loop not to continue until an event happens?

问题

我正在编写一个游戏的函数:

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

        ***

    }
    
}

在函数循环中的“if语句”在循环开始时立即运行并多次增加“i”,而不等待上面的事件完成。

我在Google和StackOverflow上搜索了使用“async await”和“promise”来解决问题,但并没有真正理解它是如何工作的,因此无法在我的代码中实现它。

英文:

I am writing a function of a game:

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.

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.

答案1

得分: 0

这应该可以工作,尽管我没有测试过它,而且你的做法不是 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;

      // 等待点击事件
      const event = await waitForClick($(".btn"));
      // 处理结果
      ButtonClickResponse(event.target.id);
      color = event.target.id;

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

      level++;
    }
  }
}

function waitForClick(element) {
  // 创建新的 Promise
  return new Promise((resolve) => {
    const handler = function (event) {
      // 当按钮被点击时移除监听器
      element.off("click", handler);
      // 并解决 Promise
      resolve(event);
    };
    // 监听点击事件
    element.on("click", handler);
  });
}
英文:

This should work, although I didn't test it and you do things not in javascript way

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

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

      // await for the click event
      const event = await waitForClick($(&quot;.btn&quot;));
      // 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) =&gt; {
    const handler = function (event) {
      // when button is clicked remove listener
      element.off(&quot;click&quot;, handler);
      // and resolve the promise
      resolve(event);
    };
    // listen for click
    element.on(&quot;click&quot;, handler);
  });
}

huangapple
  • 本文由 发表于 2023年1月8日 22:56:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定