-1

I have created a service file in angular for timer

  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 want to call 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);
}

Getting null value in console.

I want to show timer in my component like if 05:00 minutes then this timer should decrease every second in the component called in which it is called till time left is 00:00 seconds.

Thanks

user3653474
  • 3,393
  • 6
  • 49
  • 135
  • 1
    Have you checked: https://stackoverflow.com/q/46316259/5468463 – Vega Jun 23 '22 at 14:48
  • @Vega yes I have implemented the same timer and it is working but I want to create a service for that and use it in my component that's the main issue, you can check my starttimer code they are same in the link that you hav provided – user3653474 Jun 23 '22 at 17:45
  • Have you thought about disclosure? Even it is free to serve, the disclosure is the last you can do. Even not an upvote, :/ – Vega Jun 23 '22 at 18:19
  • I think I have put service option in that answer – Vega Jun 23 '22 at 18:20
  • @Vega Thanks can you please tell me if have to unsubscribe also or this is `this.countDown = this.timerService.getCounter(this.tick).subscribe(() => this.counter==0 ? this.countDown=null : this.counter-- );` sufficient when value reaches to 0, i don't have much idea about angular – user3653474 Jun 24 '22 at 09:28

2 Answers2

0

You might want to consider putting the functions you want to init in to ngOnInit() function like so

ngOnInit(): void {
 this.timerService.start_countdown();
}

Try this in side your startTimer() function,

var timer = duration, minutes, seconds;
var x = setInterval(() => { 
    minutes = (timer / 60) | 0;
    seconds = (timer % 60) | 0;
    if(timer>=0){
        timer=timer-1
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        var second_left = minutes + ":" + seconds;

        console.log(second_left);

        if(timer==0){
            console.log("cleared");
            clearInterval(x)
        }
    }
},1000)

As the constructor only call once , you will only have one 00:00 seconds console log.

Edited

One way is to use the startTimer() in the TestComponent.ts itself not the TimerUtilService , if u want to use a service you will need the observable way but this way may cause performance issues and not very idea for constant feedback.

0

You're getting a null result because the second_left variable is still undefined while invoking the console.log(this.timerService.second_left); .

Try putting a console.log in the service function and see what is happening behind the scenes like:

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(() => { 

      //##################
      // Logging timer and seconds at every interval
      //#################
      console.log("Timer: " + timer);
      console.log("Seconds left: " + second_left);        

      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);
  }
}
  • Yes i have checked it is working after adding this code `if(--timer < 0) { console.log('completed'); }` in the service file but it cannot be accessed in my other component `Output is line Timer: 149 timer-util.service.ts:24 Seconds left: 02:30 timer-util.service.ts:23 Timer: 148 timer-util.service.ts:24 Seconds left: 02:29` – user3653474 Jun 23 '22 at 14:55
  • @user3653474 did you get an error? – Dev-it-a-dev Jun 23 '22 at 15:11
  • there is no error but i cannot access the timer in my component – user3653474 Jun 23 '22 at 15:25
  • try putting a test function in your service `test(){ console.log("I'm accessible"); }` and then calling it in your component via `timerService.test();` – Dev-it-a-dev Jun 23 '22 at 15:31
  • Try changing `private timerService : TimerUtilService` to `public timerService : TimerUtilService` . This shouldn't be the problem but trying is always good :) – Dev-it-a-dev Jun 23 '22 at 15:32