React Native 中 setTimeout 的准确性 [英] Accuracy of setTimeout in React Native
问题描述
我正在用 React Native 构建一个节拍器.播放一次点击后,我为下一次点击设置了 setTimeout
.然而,时机很糟糕.
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.
我做了以下快速测试:
let time = (new Date()).getTime() + 50;
setTimeout(() => {
console.log(time - (new Date()).getTime());
}, 50)
理想情况下,我应该在控制台中得到 0.在 Chrome Dev Tools 中的 React Native 之外运行它时,我得到 -1,有时 -2(毫秒).这是一个可以接受的结果.
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.
在 macOS 上使用模拟器在 React Native 中运行它,我得到介于 0 和 -100 之间的值.这显然是不可接受的.
Running this inside React Native using the Simulator on macOS I get values between 0 and -100. This clearly is not acceptable.
有人知道这是由于setTimeout
的不准确还是(new Date()).getTime()
的不准确造成的吗?我可以解决这个问题吗?
Does someone know if this is due to the inaccuracy of setTimeout
or the inaccuracy of (new Date()).getTime()
? Can I fix this?
推荐答案
我调查了几乎所有用于播放音频的 React Native 解决方案以及使用 javascript setTimeout()/setInterval() 的各种方法,但没有一个是令人满意的时间稳定性和准确性方面.
I've investigated almost any React Native solution for playing audio and various approaches of using javascript setTimeout()/setInterval(), but none of them were satisfactory in terms of time stability and accuracy.
目前可能唯一的方法是粘贴一些像这样的原生模块:https://developer.apple.com/library/content/samplecode/HelloMetronome/Introduction/Intro.html 到 js 端,如 RN 文档中所述:https://facebook.github.io/react-native/docs/native-modules-ios.html,这给出了相当不错的结果,但不幸的是,当然,它仅适用于 iOS.
Probably the only way to go at the moment is to glue some native module like this: https://developer.apple.com/library/content/samplecode/HelloMetronome/Introduction/Intro.html to js side, as described in RN Docs: https://facebook.github.io/react-native/docs/native-modules-ios.html, which gives a pretty decent result, but unfortunately, it's iOS only, of course.
这篇关于React Native 中 setTimeout 的准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!