Last active
January 1, 2019 14:53
-
-
Save jinjor/e6f5230c4b8261d16a11b0d75ea839c5 to your computer and use it in GitHub Desktop.
Loop Problem
This file contains hidden or 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
let count = 0; | |
async function* loop() { | |
while (true) { | |
await new Promise(resolve => setTimeout(resolve, 3000)); | |
yield count++; | |
} | |
} | |
(async () => { | |
for await (const n of loop()) { | |
console.log(n); | |
} | |
})(); |
This file contains hidden or 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
let count = 0; | |
async function* loop() { | |
while (true) { | |
yield count++; | |
} | |
} | |
function start(f) { | |
let timeout = null; | |
let abort = false; | |
(async () => { | |
for await (const n of loop()) { | |
await new Promise(resolve => { | |
timeout = setTimeout(resolve, 3000); | |
}); | |
if (abort) { | |
break; | |
} | |
await f(n); | |
} | |
})(); | |
return () => { | |
timeout && clearTimeout(timeout); | |
abort = true; | |
}; | |
} | |
const end = start(async n => { | |
console.log(n); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment