Skip to content

Instantly share code, notes, and snippets.

@phobal
Created September 25, 2020 08:23
Show Gist options
  • Select an option

  • Save phobal/93f077d2106e79ebd84d7415aa9edb09 to your computer and use it in GitHub Desktop.

Select an option

Save phobal/93f077d2106e79ebd84d7415aa9edb09 to your computer and use it in GitHub Desktop.
使用 for await ...of 实现倒计时功能
// 在线 demo: https://repl.it/@phobal/forAwaitOf#index.js
let i = 60;
const items = Array(i)
.fill()
.map((_, i) => (i + 1) * 1000);
function somethingAsync(time) {
return delay(time).then(() => Promise.resolve(i--));
}
function delay(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
(async () => {
// const promises = await Promise.all(items.map(e => somethingAsync(e)));
// for (const res of promises) {
// console.log(res);
// }
i = 60; //reset counter
for await (const res of items.map(e => somethingAsync(e))) {
console.log(res);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment