jochemstoel / nodejs-system-sleep

Sleep function for Node.js All platforms.
https://www.npmjs.com/package/system-sleep
The Unlicense
51 stars 8 forks source link

Main thread should sleep but not block callbacks #9

Closed danday74 closed 7 years ago

danday74 commented 7 years ago

This code tests your library.

If the last console.log statement is executed then it works:

var sleep = require('system-sleep')
var done = false

setTimeout(function() {
  done = true
}, 1000)

while (!done) {
  sleep(100) // without this line the while loop causes problems because it is a spin wait
  console.log('sleeping')
}

console.log('If this is displayed then it works!')

This works great when using the deasync sleep.

However, when using the fallback sleep provided in the catch block (when deasync sleep is not working for whatever reason on some platform, probably a MAC) it is a spin wait. In other words, it blocks callbacks from executing. This breaks the above code and the last console.log statement is never executed. Instead the program hangs.

Please could you fix this. It would be great to see a fallback method that is as good as the deasync sleep implementation. This would make this library truly reliable across all platforms.

Currently, the fallback implementation does exactly the same as a "blocking while loop" which you refer to as bad practice (for obvious reasons) in your README.

jochemstoel commented 7 years ago

Sleep() is supposed to block those callbacks from happening.