You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中点击按钮如何重置自行创建的计时器?

你需要在resetTimer函数中补充以下逻辑即可完成计时器重置:

resetTimer() {
  // 兜底清除定时器,避免残留定时器导致后续计时异常
  clearInterval(this.interval);
  // 重置累计计时的秒数为0
  this.time = 0;
  // 重置页面展示的计时文本
  this.display = this.transform(this.time);
  console.log('reset');
}

可选优化:补全计时显示的前导零

你当前的transform方法输出的分钟、秒如果是个位数时不会补零,比如计时1秒会显示为0:0:1,视觉体验较差,可以调整为如下实现:

transform(value: number): string {
  const sec_num = value;
  const hours = Math.floor(sec_num / 3600);
  const minutes = Math.floor((sec_num - hours * 3600) / 60);
  const seconds = sec_num - hours * 3600 - minutes * 60;
  // 小于10的数字前补0
  const padZero = (num: number) => num < 10 ? `0${num}` : num;
  return `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}

内容的提问来源于stack exchange,提问作者tearex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:15:02