Code Lab

Modo entrevista. Temporizador de 8 min, sin pistas y sin autocompletado

Wait for a condition

FácilAsync code8 min

Write a function waitFor(cond, interval, timeout) that returns a promise. Call cond() at once and then every interval milliseconds.

As soon as cond() returns true, the promise resolves. If timeout milliseconds have passed and the condition is still false, the promise rejects with new Error('Timeout'). In both cases the checks stop.

Ejemplos

await waitFor(() => true, 50, 500)

Devuelve undefined

The condition is true at once, so the promise resolves with no value.
await waitFor(() => false, 50, 200).catch((e) => e.message)

Devuelve 'Timeout'

The condition never became true within 200 ms.

Fuente

Cargando el editor…
  1. The condition is true at once, no need to wait for interval
  2. The condition becomes true after 120 ms
  3. The condition is not met within 200 ms

Las pruebas ocultas se ejecutan al enviar