Avril
ed32e1586b
|
3 years ago | |
---|---|---|
README.md | 3 years ago | |
asynctimeout.js | 3 years ago |
README.md
AsyncTimeout - setTimeout()
and setInterval()
for async code.
The class AsyncTimeout(function, timeout)
.
An async wrapper around setTimeout()
, and an async iterator wrapper around setInterval()
, which resolves to/yields the return value of the supplied function for both .timeout()
and .interval()
respectively.
Methods
There are two methods on the class AsyncTimeout(func, time)
:
timeout()
: Creates anawait
able promise that will resolve to the value offunc()
when the timeouttime
is reached.interval()
: Creates afor await
able async iterator that will resolve to the value offunc()
eachtime
it is called. To cancel the interval, simply break from the loop or stop calling.next()
on the returned async iterator.
Parameters
thing
- The function to call after the timeout/interval. The result of the promise (or the yield forinterval()
) is the result of this function call. If the funtion throws, then the rejection of the promise will be that error thrown.interval
- The time to wait for the timeout or interval
Example usages
See example()
in the file for detail.
setTimeout()
promisified
await (new AsyncTimeout(() => "value", 100)).timeout() /* === "value" */
is setTimeout(()=> "value", 100)
promisified.
setInterval()
async iterator-ifyed.
for await (const value of new AsyncTimeout(() => "value", 100)).interval()) { /* value === "value" */ }
is setInterval(()=> "value", 100)
with each interval promisified.
value
will be the result of each interval call, so the function passed can capture, interact with, and return whatever it wants during the interval and each value
will be the result of it being called again at each interval (as is expected.)
This is an infinite iterator. To cancel the interval, simply break out of the for await
loop or otherwise stop using the iterator returned from .interval()
.