Waiting for Multiple Events Before Executing a Function in JavaScript

Waiting for the occurrence of multiple events before executing a function can be a bit challenging, especially when using addEventListener(), as there could be multiple events associated with the same listener.

However, if you're in a scenario where you're certain of receiving only one event, or have sufficient control to determine when the event will occur, you can convert that event into a promise.

Then, you can utilize Promise.all() to ensure consistent handling of such situations.

const movePromise = new Promise((resolve) => {
  addEventListener("pointermove", resolve, { once: true });
});

const upPromise = new Promise((resolve) => {
  addEventListener("pointerup", resolve, { once: true });
});

Promise.all([movePromise, upPromise]).then(() => {
  console.log("Both move and up events detected!");
});

This approach might not work in every situation, so other approaches may be needed. But being able to represent events like these as promises does tend to make them easier to work with.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda