Reputation: 1076
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,
Upvotes: 1
Views: 358
Reputation: 601
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
Upvotes: 1
Reputation: 13600
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.
Upvotes: 0