Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created September 5, 2022 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/6e894dbc6204cdca2940616273a54b90 to your computer and use it in GitHub Desktop.
Save bellbind/6e894dbc6204cdca2940616273a54b90 to your computer and use it in GitHub Desktop.
[ecmascript] timeout promise and inverval async iterator
export const timeout = (msec, ...args) => new Promise(f => setTimeout(f, msec, args));
export const interval = (msec, ...args) => ({
[Symbol.asyncIterator]() {
const rs = [];
const id = setInterval(() => rs.shift()?.call(undefined, {value: args, done: false}), msec);
return {
next() {
return new Promise(f => rs.push(f));
},
throw() {
//console.info("throw");
clearInterval(id);
return {value: args, done: true};
},
return() {
//console.info("return");
clearInterval(id);
return {value: args, done: true};
},
};
}
});
if (import.meta.main) (async function example() {
console.log(...await timeout(100, "hello"));
let i = 0;
for await (const v of interval(500, "world")) {
if (i++ == 5) break;
console.log(...v);
}
})().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment