Develop a TypeScript countdown timer

Seeking assistance with setInterval() in my Angular project

Here is the code snippet:

    recordingTimer: any = '00:00:00';
  timer: boolean = true;
  recording(){
    ////// Add recording meeting functionality here
    if (this.timer) {
      let seconds = 0;
      let minutes = 0;
      let hours = 0;

      seconds += 1;

      if (seconds >= 60) {
        seconds = 0;
        minutes += 1

        if (minutes >= 60) {
          minutes = 0;
          hours += 1
        }
      }

      /// Update recording time
      this.recordingTimer = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
      console.log(this.recordingTimer)

    }


  }

  repeat() {
    setInterval(() => this.recording(), 1000);
  }

Why is the console.log statement repeating with the same value of "00:00:01"?

Please provide guidance. Thank you.

Answer №1

Since the variables hour, second, and minute are local to the function and reset to zero with each call, you should consider this revised code:

// Class Variables
      seconds = 0;
      minutes = 0;
      hours = 0;

recording(){
    ///// Here is where you implement the recording meeting functionality
    if (this.timer) {

      this.seconds += 1;

      if (this.seconds >= 60) {
        this.seconds = 0;
        this.minutes += 1

        if (this.minutes >= 60) {
          this.minutes = 0;
          this.hours += 1
        }
      }

      console.log(this.hours, this.minutes, this.seconds);

      /// Update recording time
      this.recordingTimer = (this.hours ? (this.hours > 9 ? this.hours : "0" + this.hours) : "00") + ":" + (this.minutes ? (this.minutes > 9 ? this.minutes : "0" + this.minutes) : "00") + ":" + (this.seconds > 9 ? this.seconds : "0" + this.seconds);
      console.log(this.recordingTimer)

    }

Don't forget to clear these variables when you stop the timer as well.

Answer №2

Check out this straightforward timer example:

export class AppComponent {
  startTime: Date;
  stopTime: Date;
  active: boolean = false
  get display() { return (this.startTime && this.stopTime) ? +this.stopTime - +this.startTime : 0 }

  timer() {
    if (this.active) {
      this.stopTime = new Date()
      setTimeout(()=>{
        this.timer()
      }, 1000)
    }
  }

  start() {
    this.startTime = new Date()
    this.stopTime = this.stopTime
    this.active = true
    this.timer()
  }

  stop() {
    this.stopTime = new Date()
    this.active = false
  }
}

You can test it live at https://stackblitz.com/edit/angular-ivy-jezrv3

UPDATE

A modified version of the timer with pause and resume functionalities is available for demo at https://stackblitz.com/edit/angular-ivy-nds8jp

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 best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Pass a variable from one function to another for further use

I'm attempting to create a function that declares a variable, and then utilize that function within another function to access the variable. Here is my current approach: function fetchLatitude(){ navigator.geolocation.getCurrentPosition(function(l ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

The Angular-cli is unable to link to the Bootstrap framework

Trying to reference the bootstrap.css file using Angular-cli. index.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Title</title> <base href="/"> <link ...

Ways to turn off default browser tooltip using bootstrap4 tooltip

Check out the code below, which demonstrates displaying both the bootstrap tooltip and the native title-attribute tooltip: This is an example of text with a tooltip using Font Awesome icon: <i class="far fa-question-circle" data-toggle="tooltip" title= ...

Building a table using Javascript

I have been working on a JavaScript code to create a weather forecast table, but I seem to be encountering some issues. Here is the snippet of my code: for (var i = 0; i < data.list.length; i++) { table += "<tr>"; table += "<td>" + d ...

Transforming an object in TypeScript to another object while retaining the properties of the original type

Issue Struggling with TypeScript type casting here. Trying to convert an object of type B to type A, but without carrying over the properties from type B. Inquiry Is there a way to achieve this conversion without explicitly mentioning the otherName prop ...

When iterating over slice objects in a JSON file using v-for in Vue, a warning is triggered: TypeError - Attempting to access property 'slice' of

I received a JSON response from a Laravel API containing 800 items. The challenge is to display only 15 items to the user initially, with an option to load more by clicking on a 'Load More' button. Although everything seems to be functioning cor ...

Is it possible to customize the appearance of elements that are disabled using the [disabled] attribute in Angular 8?

I currently have a button on my website that triggers a form: <button (click)="create()" *ngIf="data.new" [disabled]="!dataForm.valid" color="primary" mat-raised-button> Go </button> Under specific conditions, this button disables all fiel ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this l ...

Struggling with handling multiple jQuery AJAX requests on a single webpage

Greetings, I am currently working on a PHP Project that involves loading requests using ajax. Below are the two functions in question: Function One: Upon clicking the showNotify event, an ajax request is made to retrieve content with a spinner displayed u ...

The img-wrapper is failing to show the PNG image

I'm having an issue with my code where it displays jpg images but not png. How can I make the img-wrapper show png files as well? In my example, the first image in the array is a jpg while the second is a png. However, I only see the title of the imag ...

Issue with Angular 10 Web Worker: Unable to locate the main TypeScript configuration file 'tsconfig.base.json'

Every time I attempt to run: ng g web-worker canvas I consistently encounter the error message: Cannot find base TypeScript configuration file 'tsconfig.base.json'. After thorough examination of my files, it appears that I am indeed missing a ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

Invoking a JavaScript prototype method within a different method

I have been struggling for some time now as I am not very proficient in javascript object-oriented programming. My goal is to create a callback API to detect when an element is being scrolled. However, I am facing difficulty in invoking the prototype met ...

I am experiencing difficulty transitioning the view in React Native from a side position to an inward direction

Currently tackling a design project and encountering a roadblock in achieving a specific curved effect. Here are two images for reference: The Desired Design: My Current Progress: The basic structure is in place, but hitting a wall when attempting to cu ...