'use strict';

var delay = require('delay');
var errCode = require('err-code');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var delay__default = /*#__PURE__*/_interopDefaultLegacy(delay);
var errCode__default = /*#__PURE__*/_interopDefaultLegacy(errCode);

async function waitFor(test, options) {
  const opts = Object.assign({
    timeout: 5000,
    interval: 0,
    name: 'event'
  }, options);
  const start = Date.now();
  while (true) {
    if (await test()) {
      return;
    }
    if (Date.now() > start + opts.timeout) {
      throw errCode__default["default"](new Error(`Timed out waiting for ${ opts.name }`), 'ERR_TIMEOUT');
    }
    await delay__default["default"](opts.interval);
  }
}

module.exports = waitFor;
