1

I am using javascript to send a bench of request at regular interval (every 5 ms).

I tried to use setTimeout and also sleep function, but none of them have accurate timing.

They ensure that the time interval is >= 5ms but not == 5ms. Any idea?

It seems that this very difficult to achieve in javascript or even impossible!!

This is the code I am using:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}



async function sendRequest(){ 
    var i;
    for (i=1; i<= numberOfRequests; i++){
        // send my i^th request here
        await sleep(5);
    }
}
Noureddine
  • 231
  • 2
  • 5
  • take a look at ```await sleep(5);``` – axel axel Jun 06 '19 at 07:37
  • 2
    I don't think you can guarantee the == 5ms part. You can keep a timestamp and when the setTimeout callback runs, check against the last timestamp and determine the exact time it took. Not sure if that helps or not but this is what I've seen used - if any calculations are needed, then they could be adjusted by the delta of the actual time vs the expected. – VLAZ Jun 06 '19 at 07:38
  • @axelaxel if you mean [this](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) then it's still using `setTimeout`, so it doesn't guarantee the delay – VLAZ Jun 06 '19 at 07:42
  • 4
    Possible duplicate of [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) – Code Maniac Jun 06 '19 at 07:46

2 Answers2

1

There isn't any way to provide exact timeouts in any programming language as much as they live in a general purpose multiprogrammed operating system. That happens because the exact moment the operating system will give its time slice to a particular process is just unpredictable.

Furthermore, JavaScript is single-threaded and it works with an event loop system, and the asyncrhonous tasks (such as setTimehout, xhr callback, click listeners and so on) will be executed only after that all the current code is finished. For example, if you have:

setTimeout(() => console.log('hello world'), 500);
for (let i = 0; i<1E100; i++) {
  console.log(Math.sqrt(i));
}

Hello world will be only printed only after all the calculations are completed.

Cristian Traìna
  • 7,056
  • 1
  • 31
  • 51
  • But the inaccuracy is too important sometimes one second sometimes more... – Noureddine Jun 06 '19 at 07:56
  • Then you should split your synchronous code in several asynchronous task. It's a clear sign that you have too much synchronous code – Cristian Traìna Jun 06 '19 at 07:57
  • "*JavaScript is single-threaded*" it isn't, though. *A lot* of the time, the code you write will be run in a single thread but JS itself is not single-threaded. You can have [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) to tap into multi-threaded programming and a browser can run each tab in a separate thread, too. – VLAZ Jun 06 '19 at 07:57
  • Well, also NodeJS can use several thread, it depends on the environment context. But we use to say that it's single-threaded since if you are using more threads then you know what you're doing – Cristian Traìna Jun 06 '19 at 08:04
  • Btw, there was a question on SO about how to interrupt a syncrhonous task to allow asynchronous functions to be executed, but I can't find it anymore. If someone remembers it, could you link it for OP? – Cristian Traìna Jun 06 '19 at 08:08
  • But how to split for loop to multiple asynchronous tasks? – Noureddine Jun 06 '19 at 08:19
0

Since javascript uses a single threaded event loop there is no way to obtain that accuracy. The events in the event loop are executed when the engine has finished the previous task. If you set a task to be executed after 20 ms (setTimeout, setInterval or any other custom task) the engine will add that task to the event loop then it will try to run any other task from the loop (let's assume a function that takes 25 ms to run). Since javascript is single thread, you can start any other element from the loop, until the 25ms task is finished. In that case, your timeout will start after 25 ms, even if you set it to 20. This is how javascript architecture works.

Even if you implement multi thread (workers, threads etc.) the event loop will still be present in each of them (each thread has its own loop)

Cosmin Staicu
  • 1,514
  • 2
  • 18
  • 21