Repeat a callback every ms with tick limits and early stop
A crypto price widget polls for new quotes on a fixed schedule. Some screens poll forever until the user leaves, some poll a fixed number of times, some want the first quote right away, and the poller itself sometimes decides it is done (for example, once an order is filled). Juggling raw interval ids for all of that is error-prone, so you are building one helper.
Implement repeatEvery(callback, ms, options). It calls callback on a schedule and returns a stop function.
const stop = repeatEvery(callback, ms, { times, immediate });
stop(); // => true if this call stopped a running repeater, else false
callback is called every ms milliseconds: the first call happens ms after repeatEvery is called, the second 2 × ms after, and so on.1: callback(1), callback(2), …options is optional, and so is each field in it.immediate (default false): when true, the first call (tick 1) happens synchronously inside repeatEvery, and the later calls follow every ms after that.times (default Infinity): the maximum number of calls. After the last allowed call, the repeater stops on its own. With times: 0, callback is never called.callback returns exactly false, the repeater stops after that call. Any other return value (including 0, null and undefined) keeps it running.stop() cancels all future calls. It returns true if the repeater was still running, and false if it had already stopped (by an earlier stop(), by reaching times, or by callback returning false).stop() also works when called from inside callback.const stop = repeatEvery((tick) => console.log('poll', tick), 1000);
// after 1s: poll 1, after 2s: poll 2, after 3s: poll 3
stop(); // => true
stop(); // => false
repeatEvery((tick) => console.log('quote', tick), 500, { immediate: true, times: 3 });
// right away: quote 1, after 0.5s: quote 2, after 1s: quote 3, then it stops
repeatEvery((tick) => {
const filled = checkOrder();
return filled ? false : undefined; // stop polling once the order is filled
}, 2000);
Tests replace setTimeout, setInterval, clearTimeout and clearInterval with a fake clock and move time forward by hand. Use those globals (either style works) rather than other timing APIs.