sleep() 的 JavaScript 版本是什么? [英] What is the JavaScript version of sleep()?

查看:36
本文介绍了sleep() 的 JavaScript 版本是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比以下 pausecomp 函数(取自此处)?

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

这不是 在 JavaScript 中睡眠 - 动作之间的延迟;我想要在函数中间真正的睡眠,而不是在一段代码执行之前延迟.

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

推荐答案

使用:

  await new Promise(resolve => setTimeout(resolve, 2000));

确保您的调用函数是异步的.这已经过验证并且工作正常.

Make sure your calling function is async. This is verified and is working fine.

这篇关于sleep() 的 JavaScript 版本是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆