I've developed a timer service file in Angular for countdown functionality
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TimerUtilService {
initial_module_timer_value = 300;
second_left:any;
module_finish_interval;
time_limit_over:any=false;
constructor() { }
start_countdown()
{
this.startTimer(this.initial_module_timer_value);
}
startTimer(duration) {
var timer = duration, minutes, seconds;
var self = this;
this.module_finish_interval= setInterval(() => {
minutes = (timer / 60) | 0;
seconds = (timer % 60) | 0;
if(timer>=0)
{
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
this.second_left = minutes + ":" + seconds;
}
if(--timer < 0)
{
console.log('completed');
}
},1000);
}
end_countdown()
{
clearInterval(this.module_finish_interval);
}
}
In my component, I aim to utilize this service
import { TimerUtilService } from '../../../shared/timer-util.service';
export class TestComponent implements OnInit {
constructor(private route: ActivatedRoute,private elem: ElementRef,private router: Router,private http: HttpClient,private timerService : TimerUtilService) {
this.timerService.start_countdown();
console.log(this.timerService.second_left);
}
The console displays a null value.
I intend to display a countdown timer in my component where it steadily decreases until reaching 00:00 seconds.
Thank you