Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Workers: SetInterval and SetTimeout reliability

In a browser environment, setTimeout and setInterval aren't reliable for accuracy - where time sensitivity is an issue.

Recently, we've been given requestAnimationFrame, which allows us to do a little better (in terms of performance.now() and its timestamps).

Long story short - I decided to build a metronome in Javascript, and while it works, it's fairly inaccurate above a certain tempo. While compensating for late frames allows the tempo not to desync over time, the individual beats are slightly off, which doesn't work for a metronome. (This is not a problem for animation, as it by nature doesn't need to be discrete.)

Right now, I have the option of attempting to perform a lookahead based on a threshold that I specify, to attempt to place the click between available frames (using setTimeout in the animation loop). I imagine, though, that I'll run into similar problems as setTimeout isn't reliable in the browser due to the event loop, unless the HTML5 Audio API will allow you to delay playback by a number of milliseconds.

My question: Are setTimeout and setInterval more accurate and reliable in a web worker vs the browser environment?

like image 723
jedd.ahyoung Avatar asked Nov 27 '14 02:11

jedd.ahyoung


People also ask

Is setInterval reliable?

From the above code, we can see that setInterval is always inaccurate. If time-consuming tasks are added to the code, the difference will become larger and larger ( setTimeout is the same).

Is setTimeout accurate?

It's not supposed to be particularly accurate. There are a number of factors limiting how soon the browser can execute the code; quoting from MDN: In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

Why JavaScript timer is unreliable and how can you fix it?

Using Date Object A notable difference you can see here is that the timer, although frozen due to function call, resumes at the correct time as soon as the main thread gets free. This ensures the timer always remains accurate irrespective of any heavy processing on the main thread.

Is setTimeout heavy?

No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.


1 Answers

We can say 'yes' for your question, Web workers are reliable for settimeout and setinterval functions,because web workers runs on background according to ui, so they provide you non-blocking ui events(they might affect metronome tempo), while you are processing the continuing metronome timing.

By the way there is a good doc about web workers in here.

like image 157
İlker Korkut Avatar answered Oct 23 '22 18:10

İlker Korkut