我正在试着做一个秒表(00:00:00:00).But我的一秒钟比真实的一秒钟慢。我还将setInterval 10的值更改为1,但没有什么变化。当我把它改为100时,它起作用了,时间流动得更慢了。(00:00:00:00)=(hh:mm:ss:ms)这里是我代码的一部分:
const [time, setTime] = useState({
ms: 0,
ss: 0,
mm: 0,
hh: 0
})
let degisenMs = time.ms,
degisenH = time.hh,
degisenM = time.mm,
degisenS = time.ss;
const run = () => {
if (updatedMs === 100) {
updatedS++;
updatedMs = 0
}
if (updatedS === 60) {
updatedM++;
updatedS = 0;
}
if (M === 60) {
updatedH++;
updatedM = 0
}
updatedMs++;
return (setTime({
ms: updatedMs,
ss: updatedS,
mm: updatedM,
hh: updatedH
}))
}
const start = () => {
setStatus(1)
run()
setInterv(setInterval(run, 10))
}
发布于 2020-12-22 22:58:05
问题是setInterval
不是精确的,而是近似。一种选择是使用web工作者来提高链接中所描述的准确性,但它仍然不精确。
当涉及到测量时间时,最好跟踪start
时间戳,并计算出在每次滴答/更新时已经过去了多少时间。然后,您可以更新UI或触发警报等等。下面是一些伪代码。
const [ startTime, setStartTime ] = useState(null)
const [ intervalId, setIntervalId ] = useState(null)
function tick() {
const now = new Date()
const elapsedMs = now - startTime
// Update UI etc using elapsedMs
}
function start() {
setStartTime(new Date())
// Run tick() every 100ms
setIntervalId(setInterval(tick, 100))
}
function stop() {
clearInterval(intervalId)
}
https://stackoverflow.com/questions/65416774
复制相似问题