setInterval Using setTimeout
MediumP2Coding
Implement mySetInterval(fn, delay, ...args) and myClearInterval(id) using only setTimeout and clearTimeout (do not call setInterval).
mySetIntervalcallsfn(...args)repeatedly, everydelaymilliseconds, and returns an id that identifies the interval. The first call happens afterdelayms, not immediately. The next wait starts afterfnreturns.myClearInterval(id)stops that interval. It must work when called from insidefn(no further call may happen), and calling it with an unknown or already cleared id does nothing.- Different intervals have different ids and do not affect each other.
Example 1
- Input
- const id = mySetInterval(() => log('tick'), 100); // later myClearInterval(id);
- Output
- 'tick' is logged every 100 ms until cleared
Constraints
- 1 <= delay <= 10^4
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.