简体   繁体   English

为什么NodeJS中的睡眠无法按预期工作

[英]why sleep in nodejs doesn't work as expected

I use this library to sleep inside a loop, my loop look like this 我用这个在一个循环中睡觉,我的循环看起来像这样

while(condition){
    usleep(1)
    while(condition){
        usleep(1)
        // ... do stuff (sync)
    }
}

althought i'm sleeping only for 1us, the loop never terminate it just take very very long time, but when i remove the sleep statement, it just run and done. 虽然我只睡1us,但循环永远不会终止,只需要很长的时间,但是当我删除sleep语句时,它就会运行并完成。

I'm trying to sleep to make the CPU calms down and not use 100% so the server keep accepting other requests! 我正在尝试使CPU平静下来,并且不使用100%,因此服务器继续接受其他请求!

Using setTimeout inside a loop is not a good idea, because setTimeout is async. 在循环内使用setTimeout并不是一个好主意,因为setTimeout是异步的。

I thought using recursion, but i'm afraid it will be too slow, i'm iterating arount 100000 我以为可以使用递归,但恐怕会太慢,我要遍历100000

Sleep blocks the current thread, so this effectively will not help you try to accept other requests. 睡眠会阻塞当前线程,因此这实际上将无法帮助您尝试接受其他请求。 You can try something like sleep-async to do the job. 您可以尝试使用诸如sleep-async之类的方法来完成这项工作。

If you really need to keep that code the way it is now, use Promises and async/await . 如果您确实需要按现在的方式保留该代码,请使用Promises和async / await That way your application won't be blocked for other requests. 这样,您的应用程序将不会因其他请求而被阻止。

Something like this for you to start: 像这样的东西让您开始:

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

async function run() {
    while(condition){
        await sleep(1000);
        // ... do stuff
    }
}

run().catch(err => console.error(err));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM