JavaScript time_nanosleep
Delay for a number of seconds and nano seconds
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 | function time_nanosleep (seconds, nanosecs) { // Delay for a number of seconds and nano seconds // // version: 1008.1718 // discuss at: http://phpjs.org/functions/time_nanosleep // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: For study purposes. Current implementation could lock up the user's browser. // % note 1: Consider using setTimeout() instead. // % note 2: Note that the following function's argument, contrary to the reference to // % note 2: nanoseconds, does not start being significant until 1,000,000 nanoseconds (milliseconds), // % note 2: since that is the smallest unit handled by JavaScript's Date function. // * example 1: time_nanosleep(1, 2000000000); // delays for 3 seconds // * returns 1: true var start = new Date().getTime(); while (new Date() < (start + seconds*1000+nanosecs/1000000)) {} return true; } |
Examples
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have time_nanosleep goodness in JavaScript.
@Andyk: Yes, that is true on both points (though as far as your second point, in order to follow PHP's behavior strictly, we have chosen a synchronous implementation). That is why there is a note about this being only for study purposes.
Hey just so you know this isn't very useful code. Two problems -
1) javascript date doesn't support nanoseconds, so trying to sleep for a certain amount of them is misleading.
2) its better to use settimeout, which returns control back to the browser and the system, instead of going around and around your while loop, which will actually take a lot of CPU time/power for no reason.


Jimbastard
Aug 3rd