Unlocked

waitFor.js

Nov 1st, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  *
  3.  * @param {() => boolean} pred
  4.  * @param {{
  5.  *  delay?: number,
  6.  *  maxAttempts?: number
  7.  * }} [options]
  8.  * @returns {Promise<void>}
  9.  */
  10. export const waitFor = (pred, options) => new Promise((resolve, reject) => {
  11.     options = {
  12.         delay: 100,
  13.         maxAttempts: -1,
  14.         ...options
  15.     };
  16.     let attempts = options.maxAttempts;
  17.     const loop = () => {
  18.         if (attempts-- === 0){
  19.             reject(new Error("Max attempts exceeded."));
  20.         }
  21.         if (pred()){
  22.             resolve();
  23.         }
  24.         setTimeout(loop, options.delay);
  25.     }
  26.     loop();
  27. });
Advertisement
Add Comment
Please, Sign In to add comment