How to let JavaScript wait until certain event happens?

Viewed 52790

I am writing a webpage with the following structure:

  1. One section (table A) depends on another section (table B);
  2. Another section (table B) has elements that require recalculation on each update. The calculation is handled by external tools, and will cause an event when finished.

In order to guarantee correctness, the table need to be updated only after the other table is fully updated (i.e., done with computation). However, I don't know how to effectively achieve this, and I could not find any wait facility within JavaScript.

For now, I am using the following method:

  1. Declare a global variable updated and make it false;
  2. After the first table received input, I make an empty while loop until updated is true;
  3. Add an listener, once the calculation is done and the event received, set updated to true.

This seems unintuitive to me but I cannot think of any other way of doing it. Is there any good ways to do this?

Thanks for any inputs!

4 Answers

In 2022, it's useful to have an event listener that fires off a Promise (which can be used in promise-chains, or async/await code). A clean way to make one:

function getPromiseFromEvent(item, event) {
  return new Promise((resolve) => {
    const listener = () => {
      item.removeEventListener(event, listener);
      resolve();
    }
    item.addEventListener(event, listener);
  })
}

async function waitForButtonClick() {
  const div = document.querySelector("div")
  const button = document.querySelector("button")
  div.innerText = "Waiting for you to press the button"
  await getPromiseFromEvent(button, "click")
  div.innerText = "The button was pressed!"
}
waitForButtonClick()
<button>ClickMe</button>
<div></div>

Related