export default class Polling {
  constructor(callback = () => Promise.resolve(), duration = 1000) {
    this.callback = callback;
    this.duration = duration;
    this.timeout = undefined;
  }

  #sleep() {
    this.end();
    return new Promise((resolve) => {
      this.timeout = setTimeout(resolve, this.duration);
    });
  }

  async start(payload) {
    this.callback(payload)
      .then(() => {
        this.#sleep().then(() => this.start(payload));
      });
  }

  end() {
    if (!this.timeout) {
      return;
    }

    clearTimeout(this.timeout);
  }
}