I'm trying to create a timer that lasts two hours and when it reaches zero it restarts, but I have no idea how to do it, this is what I have:
TS component
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
@Component({
selector: 'app-mantenimiento',
templateUrl: './mantenimiento.component.html',
styleUrls: ['./mantenimiento.component.css']
})
export class MantenimientoComponent implements OnInit {
_second = 1000;
_minute = this._second * 60;
_hour = this._minute * 60;
_day = this._hour * 24;
end: any;
now: any;
day: any;
hours: any;
minutes: any;
seconds: any;
source = timer(0, 1000);
clock: any;
constructor(){}
ngOnInit(){
this.clock = this.source.subscribe(t => {
this.now = new Date();
this.now.setSeconds(3600) ;
this.end = new Date();
this.showDate();
});
}
showDate(){
let distance = this.end - this.now;
this.day = Math.floor(distance / this._day);
this.hours = Math.floor((distance % this._day) / this._hour);
this.minutes = Math.floor((distance % this._hour) / this._minute);
this.seconds = Math.floor((distance % this._minute) / this._second);
}
}
HTML code:
<section>
<div class="coming-soon">
<div class="time-countdown">
<ul>
{{hours}} horas
{{minutes}} minutos
{{seconds}} segundos
</ul>
</div>
</div>
</section>
So far I only got this result:
At the moment it only behaves with negative numbers and a very strange negative countdown, I would need to add 1 hour to time.now and thus subtract the current time plus one hour minus the final time but I still don't know how to do it, I appreciate your collaboration
It's pretty straightforward using a library like
date-fns
.Explanation goes in comments.