Search code examples
javascripttimeouthtml5-audioweb-worker

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?


Solution

  • 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.