【问题标题】:Wait/pause code execution for given amount of time before executing certain function in JavaScript [duplicate]在JavaScript中执行某些功能之前等待/暂停代码执行给定的时间[重复]
【发布时间】:2022-11-03 15:39:04
【问题描述】:

我正在尝试用 vanila js 和 html 为我的副项目构建测验应用程序。我有一个条件,在执行某个代码之前我需要等待一段时间。如何创建以时间为参数的函数来暂停代码执行。

我尝试通过创建如下所示的等待函数来解决该问题,但它没有按预期工作。

   const wait = (milliseconds) => {
        new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, milliseconds);
        });
    };
    const execute = async () => {
        await wait(5000);
        console.log("Go To Next Question");
    };
    execute();

【问题讨论】:

  • new Promise 之前添加return 或删除wait 主体周围的大括号。现在,它没有返回任何值,所以不要等待你传入的时间。

标签: javascript ecmascript-6 promise function-call


【解决方案1】:

你做的一切都很好。您刚刚错过了您定义的等待函数中的返回。

 const wait = (milliseconds) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, milliseconds);
        });
    };
    const execute = async () => {
        await wait(5000);
        console.log("Go To Next Question");
    };
    execute();

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 2015-06-02
    • 1970-01-01
    • 2012-03-15
    • 2020-01-15
    • 2014-01-27
    • 1970-01-01
    • 2013-01-17
    • 2020-06-20
    相关资源
    最近更新 更多