Build a Virtual Clock for Timers
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write createClock(), a fake clock for testing code with timers, without waiting for real time. It returns an object with four methods, and its time starts at 0. now() returns the current time. setTimeout(fn, delay) schedules fn to run once the time reaches now() plus delay (delay is 0 or more) and returns an id. clearTimeout(id) cancels that timer if it hasn't run yet; an unknown id is ignored. advance(ms) moves time forward by ms, running every timer that falls due by then, in order of due time, and timers due at the same time in the order they were scheduled. While a timer runs, now() returns its due time; afterwards it returns the old time plus ms. A timer scheduled or cancelled by a running timer counts too: if it falls due within the same advance, it runs in it. Use no real timers.
Your code must pass
- Runs timers in order of due time, ties in the order scheduled
- Only runs timers that are due
- Shows each timer's due time while it runs
- Runs timers that a timer schedules within the same advance
- Cancels timers with clearTimeout