将SetInterval设置为10ms花费的时间超过了预期

问题描述

我试图在我的应用程序中创建一个秒表,并为此设置一个间隔,使其每10ms运行一次,并且在每10ms运行一次的函数内部更新时间。这里的问题是,当我运行它时,百毫秒(10ms)的运行速度非常慢,好像我已经放置了100ms。

const HomeScreen = ({ route,navigation }: Props) => {
  const [time,setTime] = useState({ ms: 0,s: 0,m: 0 });
  const [interv,setInterv] = useState();
  const [status,setStatus] = useState(0);
  // Not started = 0
  // started = 1
  // stopped = 2

  const start = () => {
    run();
    setStatus(1);
    setInterv(setInterval(run,10));
  };

  var updatedMs = time.ms,updatedS = time.s,updatedM = time.m;

  const run = () => {
    if (updatedS === 60) {
      updatedM++;
      updatedS = 0;
    }
    if (updatedMs === 100) {
      updatedS++;
      updatedMs = 0;
    }
    updatedMs++;
    return setTime({ ms: updatedMs,s: updatedS,m: updatedM });
  };

  const stop = () => {
    clearInterval(interv);
    setStatus(2);
  };

  const reset = () => {
    clearInterval(interv);
    setStatus(0);
    setTime({ ms: 0,m: 0 });
  };

  const resume = () => start();

  ...

解决方法

setInterval的问题在于它取决于引擎处理代码和其他各种负载。