简体   繁体   中英

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.

I'm trying to sleep to make the CPU calms down and not use 100% so the server keep accepting other requests!

Using setTimeout inside a loop is not a good idea, because setTimeout is async.

I thought using recursion, but i'm afraid it will be too slow, i'm iterating arount 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.

If you really need to keep that code the way it is now, use Promises and 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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