/**
 * Wait until a condition to be true with a default timeout of 1 second (and checking every 100ms).
 */
export const waitForCondition = async (
  condition: () => Promise<boolean>,
  waitOptions: {
    timeout: number;
    interval: number;
  } = { timeout: 1000, interval: 100 },
) => {
  const startTime = Date.now();

  const check = async () => {
    if (await condition()) {
      return;
    } else {
      if (Date.now() - startTime < waitOptions.timeout) {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve(check());
          }, waitOptions.interval);
        });
      }
    }
  };

  return check();
};

export default waitForCondition;
