简体   繁体   English

等待for循环内的click事件-与提示符()相似

[英]Wait for click event inside a for loop - similar to prompt()

This might not have the greatest title. 这可能没有最大的标题。 I'm trying to understand call back functions, and I was wondering how replacing prompt() in the following code could be achieved, without losing the for loop? 我试图理解回调函数,我想知道如何在不丢失for循环的情况下实现以下代码中的hint()替换?

for(i=0;i<4;i++){
  let x = prompt("Input an integer");
  // store input into an array
}

I've tried something like: 我已经尝试过类似的东西:

for(let i = 0; i<4; i++){
  let x = document.getElementById("someId");
  x.addEventListener("click", rcvInput(function(i){
    if(i == 3){
      x.removeEventListener("click", rcvInput)
    }
  }));
}
function rcvInput(callback){
  //store input into an array
  callback();
}

I know this can be done without the for loop, I'm more curious if callbacks could be able to pause the loop and wait for input? 我知道这可以在没有for循环的情况下完成,我很好奇回调是否可以暂停循环并等待输入?

Depending on what your end goal is, I'm pretty sure there's a better way to do it. 根据您的最终目标,我很确定有更好的方法来做到这一点。 But for the sake of doing that: 但是为了做到这一点:

You can create a method that returns a promise that resolves when a click happens. 您可以创建一个返回承诺的方法,该承诺会在单击发生时解决。 Then you can use async / await to do what you need. 然后,您可以使用async / await执行所需的操作。

By using a Promise and await ing on it, you can technically "pause" your for loop until something happens. 通过使用Promiseawait它,您可以从技术上“暂停”您的for循环,直到发生某些事情为止。 In this case, a click. 在这种情况下,请单击。

Remember the method that encloses the for loop has to be async . 请记住,包含for循环的方法必须是async

function getClick() {
  return new Promise(acc => {
    function handleClick() {
      document.removeEventListener('click', handleClick);
      acc();
    }
    document.addEventListener('click', handleClick);
  });
}


async function main() {
  for (let i=0;i<4;i++) {
    console.log("waiting for a click", i);
    await getClick();
    console.log("click received", i);
  }
  console.log("done");
}

main();

Try it in this plunkr . 在这个笨拙的人中尝试一下。

To acheieve: 实现:

for(var i=0;i<4;i++){
  let x = prompt("Input an integer"); // WAIT FOR PROMPT
  // ...
  // LOOP CODE AFTER PROMPT
}

you can use recursion: 您可以使用递归:

function promptLoop(count){
    let x =  prompt("Input an integer");
    // ...
    // LOOP CODE AFTER PROMPT
    if (count > 0) promptLoop(count - 1)
}

and use it like so: 并像这样使用它:

promptLoop(4);

Your second scenario is different, and can be adapted like so: 您的第二种情况不同,可以像这样进行调整:

function loop(count, method) {
    if (count > 0) method(() => loop(count - 1, method), count);
}

Your function would then take a next callback, like so: 然后,您的函数将执行下一个回调,如下所示:

function toBeLooped(next){
    // do stuff
    next() // continues loop 
}

loop(3, toBeLooped);

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

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