timers: introduce setInterval async iterator
Added setInterval
async generator to timers\promises. Utilises async generators to provide an iterator compatible with
for await
. This is a continuation of initial work by Fabian Cook https://github.com/nodejs/node/pull/35841 (who is also marked as co-author in this PR). The async-generator throws an AbortError
when aborted.
Note that there are some decisions I've made regarding (so-called) backpressure. If multiple iterations were completed before a value is yielded, the next iteration won't wait delay
long, but yield the next value in the next tick. In addition, if there was backpressure before the controller was aborted, the generator will emit all of the passed intervals, and only then finish the iteration. I'd be happy to change this behavior if this is not what's expected (i.e. change the generator to stop producing immediately).
See the previous PR for more information and discussions.
Example:
const {
setInterval
} = require('timers/promises');
const ac = new AbortController();
const { signal } = ac;
const interval = 10;
setTimeout(() => ac.abort(), 500);
let i=0;
for await (const value of setInterval(interval, undefined, { ref: false, signal })) {
console.log(Date.now(), i);
if(i++>=5) {
break;
}
}
-
make -j4 test
(UNIX), orvcbuild test
(Windows) passes -
tests and/or benchmarks are included -
documentation is changed or added -
commit message follows commit guidelines