【问题标题】:Why setInterval does not work correactly?为什么 setInterval 不能正常工作?
【发布时间】:2021-04-01 15:12:35
【问题描述】:

我正在尝试制作秒表 (00:00:00:00)。但我的一秒比真正的一秒慢。 我还将 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))
}

【问题讨论】:

    标签: javascript reactjs react-native setinterval stopwatch


    【解决方案1】:

    问题是setInterval 不准确,它是approximate。一种选择是使用网络工作者来提高链接中描述的准确性,但这仍然不准确。

    在测量时间时,最好跟踪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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2019-01-04
      • 2020-09-03
      • 2016-10-10
      • 2016-10-24
      • 2017-02-27
      • 2017-07-08
      相关资源
      最近更新 更多