使用 Promise 以 2 秒的间隔打印 5 到 0 的数字
我是 JavaScript 新手,正在学习 Promise。我想以 2 秒的间隔打印 5 到 0 个数字。 例如,第一次在 2 秒后打印 5,然后在 2 秒后打印 4,依此类推。 我已经编写了代码来执行此操作,但无法获得正确的输出。
var count = 5;
var i = 2;
function d()
{
let p = new Promise((resolve,reject)=>{
while(count>=0)
{
setTimeout(resolve,i*1000,count);
i= i*2;
count = count-1;
//count = count-1;
}
});
return p;
}
d().then((x)=>{
console.log(x);
});
它显示输出为 5。有人能纠正它吗?
I am new to JavaScript and was learning about promises. I want to print 5 to 0 numbers at the interval of 2 seconds each.
For example for the first time after 2 seconds print 5 and then after 2 second print 4 and so on.
I have written a code to do so but not able to get the correct output.
var count = 5;
var i = 2;
function d()
{
let p = new Promise((resolve,reject)=>{
while(count>=0)
{
setTimeout(resolve,i*1000,count);
i= i*2;
count = count-1;
//count = count-1;
}
});
return p;
}
d().then((x)=>{
console.log(x);
});
It is showing output as 5. Can anyone correct it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
async 来编写此代码要容易得多。 .await
语法...然后您可以创建一个将延迟超时毫秒的pause
函数。我们可以将其包装在
while
语句,循环直到计数为零。
It's much easier to write this using the
async ... await
syntax... you can then create apause
function that will delay by timeout milliseconds.We can wrap this in a
while
statement, looping until the count is zero.每当您编写程序时,最好量化您需要跟踪的内容。
在本例中,我们有三个组件。
一个基本的 for..loop 让我们循环遍历数字范围并排队一些 < a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="nofollow noreferrer">setTimeout 调用我们的回调:
我在此答案中放置了一些 www.w3schools.com 的链接。在那里您可以找到许多 JavaScript 问题的文档和教程。
Whenever you are writing a program, it is a good idea to quantify what it is you need to keep track of.
In this case we have three components.
A basic for..loop let's us loop over the number range and queue up some setTimeout calls with our callback:
I have put some links to www.w3schools.com in this answer. There you can find documentation and tutorials for a lot of JavaScript problems.