SetInterval 设置为 10ms 花费的时间超过预期
SetInterval set to 10ms is taking more than spected
我正在尝试在我的应用程序中创建一个秒表,为此我将间隔设置为每 10 毫秒 运行,并在函数内部设置 运行 每 10 毫秒我更新一次时间。这里的问题是,当我 运行 它时,厘秒(10 毫秒)变得非常慢,就好像我放了 100 毫秒一样。
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, s: 0, m: 0 });
};
const resume = () => start();
...
setInterval 的问题在于它取决于处理代码的引擎和各种其他负载。
我正在尝试在我的应用程序中创建一个秒表,为此我将间隔设置为每 10 毫秒 运行,并在函数内部设置 运行 每 10 毫秒我更新一次时间。这里的问题是,当我 运行 它时,厘秒(10 毫秒)变得非常慢,就好像我放了 100 毫秒一样。
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, s: 0, m: 0 });
};
const resume = () => start();
...
setInterval 的问题在于它取决于处理代码的引擎和各种其他负载。