javascript - 从开始秒数开始的计时器角度计数
问题描述
如何从某个开始的秒数开始在 Angular 中进行倒计时?另外,如果可能的话,我需要格式为 hh:mm:ss。
我试图做这样的事情,从模板调用 getAlarmDuration ,持续时间以秒为单位。
getAlarmDuration(duration: number): any {
this.countStart = duration;
setInterval(this.setTime, 1000);
}
setTime(): void {
++this.countStart;
console.log(this.pad(parseInt((this.countStart / 60).toString(), 10)) + ':' + this.pad(this.countStart % 60))
}
pad(val: any): string {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
}
else {
return valString;
}
}
提前致谢。
解决方案
您可以使用“rxjs”中的间隔并将计数器映射到所需的结果。
import { Component } from '@angular/core';
import { interval } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Count';
currentSeconds = 60;
// interval will emit every 1000ms
count$ = interval(1000).pipe(
// transform the stream to the result you want -- hh:mm:ss
map(count => this.format(count + this.currentSeconds * 1000))
);
format(seconds: number): string {
return new Date(seconds + +new Date()).toLocaleString('en-EN', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
}
这是一个指向 stackblitz示例工作示例的链接
推荐阅读
- c# - 如何自动移动 Datagridview 单元格包含的文本
- javascript - 用另一个 Observable 修改 Observable 并返回初始的 Observable
- python - 字符向量化
- javascript - 使用 JavaScript 动态访问嵌套对象值
- spring-boot - Spring boot Data JDBC + Querydsl 错误“原因:找不到类型的属性计数”
- php - PHP警告:require_once(/apps/backend/config/config.php):无法打开流:没有这样的文件或目录
- python - 修改父函数参数时带有嵌套函数的 UnboundLocalError
- python - 为什么我不能在我的 Tkinter 输入字段中输入
- scala - Spark窗口分区功能需要永远完成
- laravel - Laravel 验证器“in:”没有看到第一个元素