function* gen() {
for (let key = 0; key < 5; key++) {
setTimeout(() => yield (key), 1000);
}
}
let generator = gen();
for (const key of generator) {
console.log(key)
}
(async () => {
const sleep = duration => new Promise(resolve => setTimeout(resolve, duration));
for (let index = 0; index < 5; index++) {
console.log(`[${new Date().toLocaleTimeString()}] Index: ${index}`);
await sleep(1000);
}
})();
/*
[12:18:12] Index: 0
[12:18:13] Index: 1
[12:18:14] Index: 2
[12:18:15] Index: 3
[12:18:16] Index: 4
*/