setTimeout in a Loop
EasyP1Coding
This helper is meant to log the numbers 0 to n - 1, one per timer, but it logs n repeatedly.
Fix logInLoop(n, log) so that it schedules n timers with setTimeout(..., 0), and the timer for index i calls log(i). After all timers have run, log must have been called with 0, 1, ..., n - 1 in that order.
Keep the setTimeout per index; do not call log synchronously.
Example 1
- Input
- logInLoop(3, log)
- Output
- log is called with 0, then 1, then 2
- Why
- Each callback must remember its own index.
Constraints
- 0 <= n <= 1000
- The calls to log must happen inside setTimeout callbacks.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 5. ⌘Enter runs, ⌘⇧Enter submits.