简体   繁体   English

为什么 setInterval 不能正确工作?

[英]Why setInterval does not work correactly?

I am trying to make a stopwatch (00:00:00:00).But my one sec is slower than real one sec.我正在尝试制作秒表(00:00:00:00)。但我的一秒比真正的一秒慢。 I also changed the value of setInterval 10 to 1 but nothing changed.我还将 setInterval 10 的值更改为 1,但没有任何改变。 When I changed it as 100, it worked, time flowed slower.当我将其更改为 100 时,它起作用了,时间流逝得更慢了。 (00:00:00:00)=(hh:mm:ss:ms) Here is a part of my code: (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))
}

The problem is that setInterval is not exact, it is approximate .问题是setInterval不准确,它是近似的。 One option is to use web workers to increase accuracy as described in the link, but it is still not exact.一种选择是使用 web 工人来提高链接中描述的准确性,但它仍然不准确。

When it comes to measuring time, it is better to track the start timestamp and figure out how much time has passed at each tick/update.在测量时间时,最好跟踪start时间戳并计算出每次滴答/更新已经过去了多少时间。 You can then update the UI or trigger an alarm etc. Here is some pseudocode.然后,您可以更新 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM