使用 Promise 以 2 秒的间隔打印 5 到 0 的数字

发布于 2025-01-10 23:11:18 字数 523 浏览 0 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静赏你的温柔 2025-01-17 23:11:18

使用 async 来编写此代码要容易得多。 .await 语法...然后您可以创建一个将延迟超时毫秒的 pause 函数。
我们可以将其包装在 while语句,循环直到计数为零。

async function pause(timeout) {
    return new Promise(resolve => setTimeout(resolve, timeout))
}

async function countDown(count) {
    while (count > 0) {
        await pause(2000);
        console.log('count:', count);
        count--;
    }
}

countDown(5);

It's much easier to write this using the async ... await syntax... you can then create a pause function that will delay by timeout milliseconds.
We can wrap this in a while statement, looping until the count is zero.

async function pause(timeout) {
    return new Promise(resolve => setTimeout(resolve, timeout))
}

async function countDown(count) {
    while (count > 0) {
        await pause(2000);
        console.log('count:', count);
        count--;
    }
}

countDown(5);

缺⑴份安定 2025-01-17 23:11:18

每当您编写程序时,最好量化您需要跟踪的内容。

在本例中,我们有三个组件。

  1. 我们想要在每个“tick”上做一些事情,并且我们想知道我们在做什么“tick”。
  2. 我们想要从一个特定的数字开始倒数,直到 0。
  3. 每个“刻度”应该间隔一定的时间。

一个基本的 for..loop 让我们循环遍历数字范围并排队一些 < a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="nofollow noreferrer">setTimeout 调用我们的回调:

/**
 * CountDown
 *
 * @param {Function} callback - The callback is a function that we call each "tick"
 * @param {number} countDownFrom - The countdown starts at this number
 * @param {number} interval - the number of milliseconds between each "tick"
 */
function CountDown(
  callback,
  countDownFrom,
  interval
) {
  for (var count = 0; count <= countDownFrom; count++) {
    setTimeout(callback, (countDownFrom - count) * interval, count);
  }
}
CountDown(
  (x) => {
    console.log(x);
  },
  5,
  2 * 1000
);

我在此答案中放置了一些 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.

  1. We want to do something on each "tick", and we want to know what "tick" we are on.
  2. We want to count down from a specific number until we are at 0.
  3. Each "tick" should be separated by a set amount of time.

A basic for..loop let's us loop over the number range and queue up some setTimeout calls with our callback:

/**
 * CountDown
 *
 * @param {Function} callback - The callback is a function that we call each "tick"
 * @param {number} countDownFrom - The countdown starts at this number
 * @param {number} interval - the number of milliseconds between each "tick"
 */
function CountDown(
  callback,
  countDownFrom,
  interval
) {
  for (var count = 0; count <= countDownFrom; count++) {
    setTimeout(callback, (countDownFrom - count) * interval, count);
  }
}
CountDown(
  (x) => {
    console.log(x);
  },
  5,
  2 * 1000
);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文