Abh*_*yar 1 javascript asynchronous settimeout es6-promise
如果我想使用 setTimeout 和delay = Math.random() * 1000. 由于异步编程和事件循环,答案将是从 1 到 10 以随机顺序排列的数字。
我想要的是以上述相同的延迟按递增顺序打印数字。这可以通过 Promises 或 Async 模块来完成。我的意思是说它应该只打印一次,然后打印 2,依此类推。
任何帮助,将不胜感激。
注意:请不要给出诸如为变量添加时间并将该变量用作延迟之类的答案。
You could do this like this, using Promises and async/await
// returns a promise that resolves after the specified number of ms
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// function that will print the numbers in correct order, with delays
async function print(num) {
for (let i = 1; i <= num; i++) {
await delay(Math.random() * 1000); // wait
console.log(i); // print number
}
}
print(10); // actually execute functionRun Code Online (Sandbox Code Playgroud)
The function that actually prints the numbers is an async function, using a delay based on a promise that resolves after the specified number of milliseconds.
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |