Angular service not triggering timer

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

Answer №1

When you're seeing a null result, it could be because the second_left variable is still undefined when calling

console.log(this.timerService.second_left);
.

To troubleshoot, try adding a console.log inside the service function to track what's going on behind the scenes:

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);
  }
}

Answer №2

If you're looking to initialize certain functions, consider placing them inside the ngOnInit() function like this:

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

Give it a try within your startTimer() function as shown below:

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)

Since the constructor is only called once, you will see only one console log showing 00:00 seconds.

Revised

An alternative approach is to implement the startTimer() directly in the TestComponent.ts file instead of using the TimerUtilService. If you prefer utilizing a service, you may need to explore the observable method, but be aware that this approach could potentially lead to performance issues and may not be ideal for continuous feedback.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

What is the procedure for resetting the pagination tool?

What is the correct way to reset the paginator and navigate to the first page? Using this.page = 1 seems to be ineffective. It's worth mentioning that I am not utilizing MatPaginator. typescript: pageSizeOptions = [5, 10, 25, 50, 100]; pageSize ...

Exploring the integration of PrimeNG into an Angular 4 project

I recently integrated the PrimeNG library into my Angular 4 project. Everything seems to be in place as I can see PrimeNG in my dependencies and nodemodules folder. However, when I tried to implement a simple data table using the following code: & ...

Encountering an ng build error while attempting to include a factory in the providers array

Currently, I am working on a school project where I implemented a basic HttpFactory and included it in the provider section of app.module.ts. However, upon running ng build, I encountered the following error: ERROR in Cannot read property 'provide& ...

Navigating the intricate component tree structure in Angular 2: mastering the art of data element transmission

I'm currently exploring the concept of passing data between components in Angular 2 using Observables, Services, and Models, with the end goal of having the components update themselves automatically when a change occurs. However, I'm struggling ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

Is there a way to ensure that Tailwind CSS loads before rendering components in NextJS?

While developing my web application, I encountered an issue with the tailwind CSS styling. The styles seem to load correctly, but there is a slight delay before they take effect. This results in users seeing the unstyled version of the website briefly befo ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

ng serve: Module 'tapable' not found

After moving my Angular 5 project to a new computer, I encountered an issue when attempting to ng serve: Cannot find module 'tapable' Error: Cannot find module 'tapable' at Function.Module._resolveFilename (module.js:469:15) at ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Error encountered when trying to match routes in two separate Angular applications within an Express app: "Cannot find any routes that match

Greetings (please pardon any language errors as English is not my first language) Like many others, I have an Angular app running in Express and decided to create separate Angular apps for the admin and users (mainly because the navigation bar was becomin ...

Analyzing the elements of an array in JavaScript and making modifications to it based on their values

Looking for a Solution Current Data- id price 1001 200 1001 150 1002 300 1003 50 1002 70 1004 30 Desired Outcome id price 1001 350 1002 370 1003 ...

Tips on saving a cookie using universal-cookie

I followed a solution on Stack Overflow to set a cookie in my React application. However, the cookie expires with the session. Is there a way I can make this cookie persist beyond the session so it remains even when the browser is closed and reopened? ex ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

Attempting to use a string as an index for the type `{ firstName: { inputWarning: string; inputRegex: RegExp; }` is not allowed

const checkRegexSignUp = { firstName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, lastName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, } const change = (e: ChangeEvent<HT ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...

Transferring pictures between folders

I am currently developing an Angular app that involves working with two images: X.png and Y.png. My goal is to copy these images from the assets folder to a specific location on the C drive (c:\users\images) whose path is received as a variable. ...