Accurate javascript sleep function - javascript

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

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.

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)

Related

setTimeout triggers too late in MIDI.js

I'm using MIDI.js to play a MIDI file with several musical instruments.
The following things execute too late, how can I fix that?
First notes of the song. Like all notes, they are scheduled via start() of an AudioBufferSourceNode here.
MIDI program change events. They are scheduled via setTimeout here. Their "lateness" is even worse than that of the first notes.
When I stop the song and start it again, there are no problems anymore, but the delay values are very similar. So the delay values are probably not the cause of the problem.
(I use the latest official branch (named "abcjs") because the "master" branch is older and has more problems with such MIDI files.)
That is how JavaScript Event Loop works.
Calling setTimeout ... doesn't execute the callback function after the given interval.
The execution depends on the number of waiting tasks in the queue.
... the delay is the minimum time required for the runtime to process the request (not a guaranteed time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#zero_delays
Instead of setTimeout() you can use window.requestAnimationFrame() and calculate elapsed time for delay by yourself.
Window.requestAnimationFrame() - Web APIs | MDN
The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
... will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
performance.now() - Web APIs | MDN
https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
In our situation, we don't want to do any animation but want to just use it for a better-precision timeout.
const delayMs = 1000;
const startTime = performance.now();
function delay(func) {
const delayStartTime = performance.now();
function delayStep() {
// Run again if still elapsed time is less than a delay
if (performance.now() - delayStartTime <= delayMs) {
window.requestAnimationFrame(delayStep);
}
else
{
// Run the delayed function
func();
}
}
// Run first time
window.requestAnimationFrame(delayStep);
}
// Trying `setTimeout()`
setTimeout(() => doSomeJob('setTimeout()'), delayMs);
// Trying `delay()`
delay(() => doSomeJob('delay()'));
// Function that we'd like to run with a delay
function doSomeJob(marker)
{
const elapsedTime = performance.now() - startTime;
console.log(`${marker}: Ran after ${elapsedTime / 1000} seconds`);
}
If you run it many times, you'll see that delay() is pretty much all the time better than setTimeout(). The difference is very small because there is nothing else happens on the page. If there will be something intensive running, setTimeout() should demonstrate worse "precision".

javascript setTimeout() and using for loop after and consume the value of the for loop in the setTimeout()

My question is variant of this question: setTimeout executes after for loop in javascript
The code:
let i = 0;
setTimeout(() => alert(i), 100); // ?
// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
i++;
}
The output:
100000000
My Question:
I know that when we're using setTimeout with delay of 100 the WEB API setTimeout() will move to the queue of the eventloop and after that will get inside the call stack if it's empty and available.
We can see that this setTimeout will start after 100ms so i thought maybe the i value would be somthing like 4000+ or somthing like that.
but unfortunately (with this big loop that take like 5+- seconds that is 5000ms) the setTimeout function will be executed just after the for loop finishes! but the event loop daemon is running and ready to accept the setTimeout callback because the call stack is empty.
I know that JS concurrency concept is diffrent from languages just like JAVA&C++, etc... that there is no scheduler for the CPU time because it's one threaded language, but I guess that the event loop working like OS daemon and ready to accept the message from the queue even if the CPU is busy with the for loop.
so the reason that it's happening is because the CPU is busy and can't execute the eventloop ? or there is other reason?
Thanks guys!

Do NodeJS setInterval()s queue up?

There's a classical problem with setInterval() in browsers - if some JS code or other browser process takes too long to complete, several callback invocations might get "backed up" and you suddenly end with your callback executed multiple times in quick succession.
Often this is not what is desired when setInterval() is used. It's a typical use case when you want AT LEAST some interval of time to pass between invocations. The workaround to this is to use setTimeout() instead and only schedule the next invocation when the previous is completed.
This works well but also is extra code and might be confusing for someone who does not understand the issue.
I know that NodeJS works differently than browsers, but I cannot find any information on this particular aspect. Does NodeJS also exhibit the same behavior, or does it guarantee a minimum time between invocations when using setInterval()?
Looks like it.
start = () => {
console.log(Date.now(), 'interval started');
setInterval(() => console.log(Date.now(), '-'), 1000);
}
busy = (n) => {
console.log(Date.now(), 'busy started');
for (let i = 1; i < n; i++) Math.sqrt(i, 7);
console.log(Date.now(), 'busy done');
}
start();
busy(1e10); // this takes a while; nothing is printed, because this keeps the node.js thread busy
Output:
1642469880773 interval started
1642469880776 busy started
1642469888272 busy done
1642469888272 -
1642469889273 -
1642469890274 -
Note the long gap between busy start and done, and how no backlog of interval callbacks seem to follow.

Javascript sleep() function executed early

I am trying to figure out why in my Code section, this.sleep(5000) seems to be getting called before my draw function, because it doesn't get drawn to the canvas until after sleep is done. any insights on why this isn't working the way I want it to?
Sleep function:
sleep: function(milliseconds) {
setTimeout(function(){
var start = new Date().getTime();
while ((new Date().getTime() - start) < milliseconds){
// Do nothing
}
},0);
},
Code:
var g = new Graph(this.diagram);
g.DrawPolygons(ctx,"blue");
this.sleep(5000);
Short answer
Don't do it this way. Even if you get it to work, it will be inconsistent, will cause you many problems, and is almost globally considered bad practice.
Long answer
JavaScript runtimes are almost always designed to be asynchronous. Your while loop is intended to make everything... wait. You cannot (or at least shouldn't) do that in most JavaScript environments.
Instead, schedule events/functions to be executed some number of ms in the future. This is what setTimeout is for. This removes the need for a sleep function.
Here's what your code might look like after the changes described above are applied:
var g = new Graph(this.diagram);
g.DrawPolygons(ctx, "blue");
setTimeout(function() {
g.DrawPolygons(ctx, "red"); // Or whatever
setTimeout(function() {
g.DrawPolygons(ctx, "yellow"); // Or whatever
// etc..
}, 5000);
}, 5000);
ES2015 update - using promises
To avoid potential deeply nested setTimeouts, you can use this
const sleep ms = new Promise(resolve => setTimeout(resolve,ms));
which is simply a promise that resolves in ms milliseconds. This allows you to keep everything in one block:
var g = new Graph(this.diagram);
g.DrawPolygons(ctx, "blue");
(async () => {
g.DrawPolygons(ctx, "red");
await sleep(5000);
g.DrawPolygons(ctx, "yellow");
await sleep(5000);
// ...
})()
Note two things:
Under the hood, there are still events/callback. It looks like C's or Python's sleep but behave very differently.
You can only use this inside asynchronous functions. See here for more information.
There are several problems with the code you've posted. First off, you should never use a while loop to halt code execution.
Secondly, you're setting a timeout, which allows other code to be executed in the interim (yes, even if the timeout is zero seconds). Remove that and you should be able to pause execution (BUT DON'T DO THIS):
sleep: function(milliseconds) {
var start = new Date().getTime();
while ((new Date().getTime() - start) < milliseconds){
// Do nothing
}
},
However, occupying the JS thread means that other browser operations (redraws, etc) will be halted until your sleep function exits. Just having this code in your JS file is an antipattern, you'd be better off finding a different way to solve your problem. Read up on the XY problem and ask a new question.
In case all you wanted to do was execute some code after a certain interval without blocking everything else, setTimeout is all you need.
sleep: function(ms, funcToExecute) {
setTimeout(funcToExecute, ms);
},
(Though at this point, sleep is redundant)
This is happening because of how JavaScript's setTimeout works. When you do:
setTimeout(function(){}, 0)
You are not actually telling it to run the function after 0ms (the lowest value is actually 4ms, but that's besides the point). You are telling it to run the function in the future. What it actually does is put the function at "the end of the stack". It'll finish running the function that called it, and maybe even run some UI redraws before it runs the timeout.
If this code is ran in a loop, your timeouts will not run at all when you think they will ;)
Also, remember JavaScript is single threaded. One thread runs your code as well as the UI redraws. Doing a while loop that does nothing and waits for 5 seconds will lock up the browser. It will prevent any user interaction and UI redraws. It might even make the OS think the browser crashed. DO NOT DO THIS!
Instead, try setting a timeout to run the next polygon after 5000ms:
var g = new Graph(this.diagram);
g.DrawPolygons(ctx,"blue");
setTimeout(function(){
// Code to run after the "sleep"
// Maybe another shape
g.DrawPolygons(ctx, "red");
}, 5000);

Need JavaScript sleep() replacement

I know this is bad:
function sleep(millis) {
var date = new Date();
var curDate = null;
do { curDate = new Date();
} while(curDate-date < millis);
}
EDIT:
function doSomethingQuickly(pixelData) {
// loads an external image, filling the entire screen
// overlays $pixelsData over image
}
But I really do need this sort of functionality since doSomethingQuickly() returns so fast and the other doSomethingQuickly()'s cannot be allowed to run until the previous is finished. It would be disastrous to simply fire them all off and wait for results to deal with them.
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
My question is that since simulating sleep in JS is bad, how can I achieve the same using setTimeout() or another more acceptable method
NOTE: this is not in a web browser
EDIT:
You can see that if it ran 5 times without the sleep, it would quickly show the final image, when what it should do is 1) show an image 2) pause for 5 seconds 3) repeatYou can see that if it ran 5 times without the sleep, it would quickly show the final images, when what it should do is 1) show an image 2) pause for 5 seconds 3) repeat
How about:
function sleep(ms,callback){
setTimeout(callback,ms);
}
//basic usage
while (someStoppingcondition){
sleep(500,doSomethingQuicky);
}
if doSomethingQuicky is always the same function, setInterval (see other answers) is sufficient. Make sure it will not run forever, use clear[Interval/Timeout] to stop the timers.
if your problem is that one function has to complete before the next one executes, this may be a way to solve it:
function firstRunner(arg1,arg2,/* ... argx*/, nextRunner){
//do things
//after things are done, run nextRunner
nextRunner();
}
JavaScript is single-threaded. Any series of doSomethingQuicky(); should execute sequentially.
That is unless you're using some timer functions within doSomethingQuicky();. Without knowing what this function does, it's hard to advise.
var interval = setInterval(doSomethingQuickly, 500)
...
clearInterval(interval);
I don't know what the code is doing. JavaScript is single threaded so you shouldn't hit any problems. You also shouldn't sleep as it sleeps the only thread.
Using sleeps to wait for a function to return is always a bad idea. What if the slow function takes more time than predicted? What about time performance issues regarding the time spent idling?
Use promises instead:
// resolves immediatly to the string 'fast done'
const fast = new Promise(resolve => resolve('fast done'));
// resolves after 1 second to the string 'slow done'
const slow = new Promise(resolve => setTimeout(() => resolve('slow done'), 1000));
// resolves after 1 second to the array ['fast done', 'slow done'], then logs it for demo purposes
Promise.all([fast, slow]).then(console.log);
I think that Promise.all is exaclty what you're looking for. It resolves when all the promises that it gets as argument resolve, so you can pass it several functions with different execution time, and continue the code when all the functions have returned.

Categories