From 66a5c7cc05e12adf8052478c19a6dcde1e930767 Mon Sep 17 00:00:00 2001 From: Avril Date: Fri, 11 Feb 2022 20:56:18 +0000 Subject: [PATCH] Initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added the `AsyncTimeout(func, delay)` class, with awaitable `timeout()` and `for await`able `interval()`. Added documentation to the class Added a `example()` function that can show how it works or how to use it. Added README that has the title and what the file does. Fortune for async-timeout-js's current commit: Great blessing − 大吉 --- README.md | 3 +++ asynctimeout.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 README.md create mode 100644 asynctimeout.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..759fe18 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# AsyncTimeout - A promisified wrapper for `setTimeout()` and `setInterval()` + + diff --git a/asynctimeout.js b/asynctimeout.js new file mode 100644 index 0000000..bfd5df1 --- /dev/null +++ b/asynctimeout.js @@ -0,0 +1,46 @@ +/// An async wrapper around `setTimeout()` and `setInterval()`. +/// +/// # `setTimeout()` +/// `await (new AsyncTimeout(() => "value", 100)).timeout() /* === "value" */` is `setTimeout(()=> "value", 100)` promisified. +/// +/// # `setInterval()` +/// `for await (const value of new AsyncTimeout(() => "value", 100)).interval()) { /* value === "value" */ }` is `setInterval(()=> "value", 100)` promisified. +/// This is an infinite iterator. To cancel the interval, simply break out of the `for await` loop. +/// +/// # 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 +/// +/// # Examples +/// See `examples` below. +function AsyncTimeout(thing, interval) +{ + this.timeout = () => new Promise((resolve, reject) => { + setTimeout(() => { + try { + resolve(thing()); + } catch(e) { reject(e); } + }, interval); + }); + this.interval = async function*() => { + while(true) { + yield await new Promise((resolve, reject) => { + setTimeout(() => { + try { resolve(thing()); } catch(e) { reject(e); } + }, interval); + }); + } + }; +} + +const example = async (_timeout) => { + _timeout = _timeout || 100; + + // Wait 100 then alert "hi" + alert(await (new AsyncTimeout(() => "hi", _timeout)).timeout()); + + // Continuously wait 100 then alert "hi" + for await (const value of new AsyncTimeout(() => "hi forever", _timeout).interval()) { alert(value); } +}; + +