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

如何在Angular 11-14及JavaScript中设置dd HH:mm:ss格式计时器

实现dd HH:mm:ss格式计时器(Angular 11-14 + JavaScript)

下面分别给出原生JavaScript和Angular 11至14版本的实现方案,包含格式处理逻辑和运行效果说明(示例格式对应天、时、分、秒,如01:24:40:15)。


一、原生JavaScript实现

核心思路:通过setInterval每秒更新总秒数,将总秒数拆解为天、时、分、秒后,用padStart方法统一格式化为两位数字。

代码实现

<!-- HTML结构 -->
<div id="timer"></div>
// 初始总秒数(对应示例01:24:40:15)
let totalSeconds = 880015;
const timerElement = document.getElementById('timer');

const updateTimer = () => {
  if (totalSeconds <= 0) {
    clearInterval(timerInterval);
    timerElement.textContent = '00:00:00:00';
    return;
  }
  
  // 拆分总秒数为天、时、分、秒
  const days = Math.floor(totalSeconds / (24 * 3600));
  const remainingAfterDays = totalSeconds % (24 * 3600);
  const hours = Math.floor(remainingAfterDays / 3600);
  const remainingAfterHours = remainingAfterDays % 3600;
  const minutes = Math.floor(remainingAfterHours / 60);
  const seconds = remainingAfterHours % 60;

  // 格式化每个时间单位为两位数字
  const formattedDays = String(days).padStart(2, '0');
  const formattedHours = String(hours).padStart(2, '0');
  const formattedMinutes = String(minutes).padStart(2, '0');
  const formattedSeconds = String(seconds).padStart(2, '0');

  timerElement.textContent = `${formattedDays}:${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
  totalSeconds--;
};

// 初始化显示
updateTimer();
// 每秒更新计时器
const timerInterval = setInterval(updateTimer, 1000);

运行效果截图

计时器运行界面


二、Angular 11-14实现

Angular版本11至14的核心API差异极小,以下提供两种实现方式:组件内直接处理、自定义管道复用格式逻辑。

方法1:组件内直接处理逻辑

适合单一组件使用计时器的场景,逻辑封装在组件内部。

// timer.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `<div class="timer">{{ formattedTime }}</div>`
})
export class TimerComponent implements OnInit, OnDestroy {
  totalSeconds = 880015;
  formattedTime = '';
  timerInterval: any;

  ngOnInit(): void {
    this.updateTimer();
    this.timerInterval = setInterval(() => this.updateTimer(), 1000);
  }

  ngOnDestroy(): void {
    // 组件销毁时清除定时器,避免内存泄漏
    if (this.timerInterval) clearInterval(this.timerInterval);
  }

  private updateTimer(): void {
    if (this.totalSeconds <= 0) {
      this.formattedTime = '00:00:00:00';
      clearInterval(this.timerInterval);
      return;
    }

    const days = Math.floor(this.totalSeconds / (24 * 3600));
    const remainingAfterDays = this.totalSeconds % (24 * 3600);
    const hours = Math.floor(remainingAfterDays / 3600);
    const remainingAfterHours = remainingAfterDays % 3600;
    const minutes = Math.floor(remainingAfterHours / 60);
    const seconds = remainingAfterHours % 60;

    this.formattedTime = `${this.padWithZero(days)}:${this.padWithZero(hours)}:${this.padWithZero(minutes)}:${this.padWithZero(seconds)}`;
    this.totalSeconds--;
  }

  // 统一格式化两位数字的工具方法
  private padWithZero(num: number): string {
    return num.toString().padStart(2, '0');
  }
}

方法2:自定义Pipe(复用性更高)

适合多个组件需要使用同一种时间格式的场景,将格式逻辑封装为管道,可在模板中直接调用。

1. 创建自定义管道

// time-format.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'timeFormat'
})
export class TimeFormatPipe implements PipeTransform {
  transform(totalSeconds: number): string {
    if (totalSeconds <= 0) return '00:00:00:00';

    const days = Math.floor(totalSeconds / (24 * 3600));
    const remainingAfterDays = totalSeconds % (24 * 3600);
    const hours = Math.floor(remainingAfterDays / 3600);
    const remainingAfterHours = remainingAfterDays % 3600;
    const minutes = Math.floor(remainingAfterHours / 60);
    const seconds = remainingAfterHours % 60;

    return `${this.padWithZero(days)}:${this.padWithZero(hours)}:${this.padWithZero(minutes)}:${this.padWithZero(seconds)}`;
  }

  private padWithZero(num: number): string {
    return num.toString().padStart(2, '0');
  }
}

2. 在组件中使用管道

// timer.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `<div class="timer">{{ totalSeconds | timeFormat }}</div>`
})
export class TimerComponent implements OnInit, OnDestroy {
  totalSeconds = 880015;
  timerInterval: any;

  ngOnInit(): void {
    this.timerInterval = setInterval(() => {
      if (this.totalSeconds > 0) this.totalSeconds--;
      else clearInterval(this.timerInterval);
    }, 1000);
  }

  ngOnDestroy(): void {
    if (this.timerInterval) clearInterval(this.timerInterval);
  }
}

3. 在模块中声明管道和组件

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TimerComponent } from './timer.component';
import { TimeFormatPipe } from './time-format.pipe';

@NgModule({
  declarations: [TimerComponent, TimeFormatPipe],
  imports: [BrowserModule],
  bootstrap: [TimerComponent]
})
export class AppModule { }

Angular运行效果截图

Angular计时器界面


内容的提问来源于stack exchange,提问作者The Losers Club

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:37:37