I'm building a metronome in React Native. After playing a click, I set a setTimeout
for the next click. The timing however, is awful.
I did the following quick test:
let time = (new Date()).getTime() + 50;
setTimeout(() => {
console.log(time - (new Date()).getTime());
}, 50)
Ideally, I should get 0 in the console. While running this outside React Native in Chrome Dev Tools, I get -1, sometimes -2 (ms). This is an acceptable result.
Running this inside React Native using the Simulator on macOS I get values between 0 and -100. This clearly is not acceptable.
Does someone know if this is due to the inaccuracy of setTimeout
or the inaccuracy of (new Date()).getTime()
? Can I fix this?
I've investigated almost every React Native solution for playing audio and various approaches of using JavaScript's setTimeout
/setInterval
, but none of them were satisfactory in terms of time stability and accuracy.
Probably the only way to go at the moment is to glue some native module like this one to the JS side, as described in the RN Docs. This gives a pretty decent result, but is iOS only, of course.