Eltorrooo
Eltorrooo

Reputation: 197

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

Upvotes: 0

Views: 1392

Answers (2)

Alex K
Alex K

Reputation: 7217

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

Upvotes: 0

skeddels
skeddels

Reputation: 57

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.

Upvotes: 3

Related Questions