Search code examples
javascripthtmltiming

Reducing Jitter in HTML5/Javascript App


I'm building for a hobby a metronome in JavaScript/HTML5 (should be eventually a FirefoxOS app). The problem I have is Jitter, which is a no-go for Metronomes. I understand that JavaScript is single-threaded and no controls about process priority exist. This is what I have:

function tick() {
    var next_tick_bpm = parseInt(document.getElementById("bpm").value);
    if (started) {
            if (next_tick_bpm > 0) {
                    var next_tick_ms = 60000 / next_tick_bpm;
                    beep();
                    setTimeout(tick, next_tick_ms);
            } else {
                    toggle();
            }
    }

}

Is there something else besides setTimeout (I also tried setInterval with the same results)? Maybe some native browser code for more precise timers?

Thanks,

  • Johannes

Solution

  • Since JS runs on the UI thread and shares it with all other activity, you absolutely cannot remove jitter with simple tools like timeout and interval. The problem is that these merely put you into the queue periodically, and always in the back.

    Instead, you should look at Web Workers, which offer a mechanism for pushing long running tasks (like a metronome) off the main thread.

    Some good info here:

    https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers