React Native定时器暂停后重启出现数秒跳转问题如何解决
问题根因
- 核心逻辑错误:
_calculateDuration始终以首次启动的startTime作为时间计算起点,没有排除定时器暂停阶段的时间差。比如你计时10秒后暂停了5秒再重启,重启瞬间计算时长会直接用当前时间减去首次启动时间,得到15秒的结果,也就是你观测到的「提前跳转数秒」现象。 - 额外隐患:
_stopTimer方法返回的Promise从未调用resolve(),外部如果用await调用该方法会永久卡住。
修复方案
首先调整实例变量和初始化逻辑,新增变量存储暂停前已经累计的有效时长,以及记录每次恢复计时的起始时间:
constructor(props) { super(props); this.timer = null; // 新增:存储暂停前已经累计的有效时长(毫秒) this.accumulatedMs = 0; // 新增:存储每次恢复/启动计时的实际开始时间戳 this.currentSessionStart = null; this.state = { duration: props?.duration || '00:00:00', // 可以保留原startTime用于业务上报,不参与计时逻辑计算 startTime: props?.started ? moment(props.started).format('YYYY-MM-DD HH:mm:ss') : null, stopTime: props?.stopped ? moment(props.stopped).format('YYYY-MM-DD HH:mm:ss') : null, }; }
修改_startTimer方法,适配新的计时逻辑:
async _startTimer() { if (this.timer) clearInterval(this.timer); let stateUpdate = { stopTime: null, }; if (!this.state.startTime) { const newStartTime = moment(Date.serverTime() || Date.now()); stateUpdate.startTime = newStartTime.format('YYYY-MM-DD HH:mm:ss'); } // 首次启动时重置累计时长,记录本次会话开始时间 this.accumulatedMs = 0; this.currentSessionStart = Date.serverTime() || Date.now(); this.setState(stateUpdate, () => { this.timer = setInterval(() => { const newDuration = this._calculateDuration(); this.setState({ duration: newDuration, }); }, 1000); if (this.props.onChange) this.props.onChange(this.state); }); };
修改_stopTimer方法,停止时计算本次会话的有效时长累加到总累计值,同时补全Promise resolve:
_stopTimer() { return new Promise((resolve) => { if (this.timer) clearInterval(this.timer); // 停止时累加本次会话的有效时长 const now = Date.serverTime(); this.accumulatedMs += now - this.currentSessionStart; const newStopTime = moment(now); this.setState({ stopTime: newStopTime.format('YYYY-MM-DD HH:mm:ss'), }, async () => { if (this.props.onChange) await this.props.onChange(this.state); // 补全resolve调用 resolve(); }); }); };
修改_calculateDuration方法,基于累计时长+当前会话时长计算总时长:
_calculateDuration() { // 如果已经停止,直接返回当前已存的总时长 if (this.state.stopTime) { return moment.utc(this.accumulatedMs).format('HH:mm:ss'); } // 运行中时长 = 累计历史时长 + 当前会话已跑时长 const currentSessionMs = (Date.serverTime() || Date.now()) - this.currentSessionStart; const totalMs = this.accumulatedMs + currentSessionMs; return moment.utc(totalMs).format('HH:mm:ss'); };
修改_continueTimer方法,重启时仅更新当前会话的开始时间,不清空累计时长:
async _continueTimer() { if (this.timer) clearInterval(this.timer); this.setState({ stopTime: null, }, () => { // 恢复计时时仅重置当前会话的开始时间 this.currentSessionStart = Date.serverTime() || Date.now(); this.timer = setInterval(() => { const newDuration = this._calculateDuration(); this.setState({ duration: newDuration, }); }, 1000); if (this.props.onChange) this.props.onChange(this.state); }); };
内容的提问来源于stack exchange,提问作者Muirik
相关产品推荐
相关产品推荐

