'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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1