OStack程序员社区-中国程序员成长平台

标题: What is the JavaScript version of sleep()? [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-10 16:07
标题: What is the JavaScript version of sleep()?

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);
}

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.



Best Answer-推荐答案


2017 — 2021 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Or as a one-liner:

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

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

Use it as:

await sleep(<duration>);

Demo:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    for (let i = 0; i < 5; i++) {
        console.log(`Waiting ${i} seconds...`);
        await sleep(i * 1000);
    }
    console.log('Done');
}

demo();





欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4