Latest Information using Atomics.wait
This code is compatible with Node.js version 9.3 and above.
I was in need of an accurate timer for Node.js tasks, and this method proved to be very effective.
However, it appears that browser support for this feature is quite limited.
let ms = 10000;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
I conducted several 10-second timer tests.
Using setTimeout, the margin of error was found to be up to 7000 microseconds (7 ms).
On the other hand, with Atomics, the error margin seems to remain under 600 microseconds (0.6 ms).
2020 Update: Recap
function sleep(millis){ // Requires assistance of a server-side page
let netMillis = Math.max(millis-5, 0); // Assuming 5 ms overhead
let xhr = new XMLHttpRequest();
xhr.open('GET', '/sleep.jsp?millis=' + netMillis + '&rand=' + Math.random(), false);
try{
xhr.send();
}catch(e){
}
}
function sleepAsync(millis){ // Recommended for async functions only
let netMillis = Math.max(millis-1, 0); // Assuming 1 ms overhead
return new Promise((resolve) => {
setTimeout(resolve, netMillis);
});
}
function sleepSync(millis){ // Designed for worker threads, currently supported in Chrome only
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);
}
function sleepTest(){
console.time('sleep');
sleep(1000);
console.timeEnd('sleep');
}
async function sleepAsyncTest(){
console.time('sleepAsync');
await sleepAsync(1000);
console.timeEnd('sleepAsync');
}
function sleepSyncTest(){
let source = `${sleepSync.toString()}
console.time('sleepSync');
sleepSync(1000);
console.timeEnd('sleepSync');`;
let src = 'data:text/javascript,' + encodeURIComponent(source);
console.log(src);
var worker = new Worker(src);
}
For those using a server-side page like sleep.jsp
, the code snippet would resemble:
<%
try{
Thread.sleep(Long.parseLong(request.getParameter("millis")));
}catch(InterruptedException e){}
%>