summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/simple_poll.js
blob: 576a9ec880cb6e52333a3a74025f58ca609442a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default (fn, { interval = 2000, timeout = 60000 } = {}) => {
  const startTime = Date.now();

  return new Promise((resolve, reject) => {
    const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
    const next = () => {
      if (timeout === 0 || Date.now() - startTime < timeout) {
        setTimeout(fn.bind(null, next, stop), interval);
      } else {
        reject(new Error('SIMPLE_POLL_TIMEOUT'));
      }
    };
    fn(next, stop);
  });
};