1

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
Johannes Thoma
  • 1,026
  • 10
  • 21
  • Hi, anyone else who is looking for precise timing requirements for FirefoxOS? I didn't have a chance to try this on a native FirefoxOS phone yet, but I suppose there will be limitation in the accuracy of setInterval and friends. Does anybody know about a working metronome app under firefoxOS? – Johannes Thoma Nov 12 '13 at 17:10

2 Answers2

1

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

Kim
  • 592
  • 3
  • 13
0

You could try something like this:

function start(speed) {
   return setInterval(beep, 60000/speed);  
}

function stop(iid) {
   clearInterval(iid);
}

When you want to start it, do something like:

// Start
var metronome = start(100);

// Stop
stop(metronome);

If nothing blocks the UI thread, the setInterval should give you good results.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99