Search code examples
javascriptfor-loopprompt

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(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?


Solution

  • 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.

    By using a Promise and awaiting on it, you can technically "pause" your for loop until something happens. In this case, a click.

    Remember the method that encloses the for loop has to be 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.