Search code examples
javascriptpause

How do I make the program wait for a button click to go to the next loop iteration in a method? [JavaScript]


I've made an algorithm that has many loops in it, and I'm trying to step through it with the click of the button. I need to be able to carry out just one iteration of the loop the first time I click a button, and then carry out the next iteration when I click it again, and so on until the program is finished. Can I accomplish that using JavaScript? If so, how?


Solution

  • A clean an simple way to do this is with Promises, and using async / await.

    Basically make your button click into a promise resolver that your wait function can pass.

    Example below.

    let waitForPressResolve;
    
    function waitForPress() {
        return new Promise(resolve => waitForPressResolve = resolve);
    }
    
    const btn = document.querySelector('button');
    
    function btnResolver() {
      if (waitForPressResolve) waitForPressResolve();
    }
    
    async function doIt() {
      btn.addEventListener('click', btnResolver);
      for (let c = 1; c < 10; c += 1) {
        console.log(c);
        await waitForPress();
      }
      btn.removeEventListener('click', btnResolver);
      console.log('Finished');
    }
    
    
    doIt();
    <button>Do Next</button>