Created
September 5, 2022 02:16
[ecmascript] timeout promise and inverval async iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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