const asyncPolling = (asyncFn, delay = 0) => {
  let _promise;
  let _resolve, _reject;
  let timer = null;
  
  const PROCESSING = 'PROCESSING';
  const FINISHED = 'FINISHED';
  let status = PROCESSING;

  const exec = () => {
    return _promise = new Promise((resolve, reject) => {
      _resolve = resolve;
      _reject = reject;
      asyncFn().finally(() => {
        _resolve && _resolve();
        _promise = null;
        if (status === PROCESSING) {
          timer = setTimeout(() => {
            if (status === PROCESSING) {
              exec();
            }
          }, delay)
        }
      })
    })
  }

  const startup = () => {
    cancel();
    status = PROCESSING;
    setTimeout(() => {
      if (status === PROCESSING) {
        exec();
      }
    }, delay);
  }

  const cancel = () => {
    status = FINISHED;
    _resolve = null;
    _reject = null;
    _promise = null;
    clearTimeout(timer);
    timer = null;
  }
  
  return {
    startup,
    cancel,
  }
}

export default asyncPolling;