A simple and featureful async interface for `setTimeout()` and `setInterval()`. And a simple and featureful interface for semaphores in async JavaScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
Go to file
Avril e01d0d8534
Update README
3 years ago
README.md Update README 3 years ago
asynctimeout.js Failed attempt at allowing async functions to be passed as `thing`: This will need a complete redesign to support this and I don"t care enough right now to do it. 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 an awaitable promise that will resolve to the value of func() when the timeout time is reached.
  • interval(): Creates a for awaitable async iterator that will resolve to the value of func() each time 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 for interval()) 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().