Poll Until a Condition Holds

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write pollUntil(check, { interval, timeout }). check takes no arguments and returns a value or a promise of one. Call check straight away, before pollUntil returns. If its value is truthy, resolve with that value. If not, wait interval milliseconds after that call finished, then call check again, and so on, never running two calls of check at once. If timeout milliseconds pass after pollUntil was called without a truthy value, reject with an Error whose name is "TimeoutError", and don't call check again. If check throws or its promise rejects, reject with that error and don't call check again. The checks use intervals of 10 to 50 milliseconds.

Your code must pass

  • Resolves with the first truthy value
  • Calls check straight away, then waits interval between calls
  • Never runs two checks at once
  • Rejects with a TimeoutError when time runs out
  • Stops calling check once it has settled