Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible.

I attempted to accomplish this by utilizing the getAlarmDuration function within the template with a duration specified in seconds.

getAlarmDuration(duration: number): any {
    this.countStart = duration;
    setInterval(this.setTime, 1000);
}

setTime(): void {
    ++this.countStart;
    console.log(this.pad(parseInt((this.countStart / 60).toString(), 10)) + ':' + this.pad(this.countStart % 60))
}

pad(val: any): string {
    var valString = val + "";
    if (valString.length < 2) {
        return "0" + valString;
    }
    else {
        return valString;
    }
}

Any help is greatly appreciated. Thank you.

Answer №1

To transform the counter to the desired result, you can utilize the interval feature from the 'rxjs' library and map the values accordingly.

import { Component } from '@angular/core';
import { interval } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Count';
  currentSeconds = 60;

  // Using interval to emit every 1000ms
  count$ = interval(1000).pipe(
    // Map transformation to get hh:mm:ss format 
    map(count => this.format(count + this.currentSeconds * 1000))
  );

  format(seconds: number): string {
    return new Date(seconds + +new Date()).toLocaleString('en-EN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }
}

Check out a working sample on stackblitz showcasing this implementation.

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

Gather image origins from a website, even if img tags are inserted through javascript or other methods during the page's rendering

I am looking to extract the URLs of all the images from a web page using C# and asp.net. Currently, I am utilizing: WebClient client = new WebClient(); string mainSource = client.DownloadString(URL); Afterwards, I am scanning the mainSource string for i ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

The specified 'detail' property cannot be found on the given type '{}'. Error code: 2339

I encountered the error mentioned in the title while working on the code below. Any suggestions on how to resolve this issue? Any assistance would be greatly appreciated! import { useHistory } from "react-router-dom"; let h ...

Ways to retrieve the page name where the script originates from

I have a function that is triggered from three different pages. Each page involves adding an attribute to a specific div. For instance: <div id="posts" page="home"></div> <div id="posts" page="feed"></div> <div id="posts" page= ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

How to include a javascript file in a vuejs2 project

Just starting out with the Vue.js framework and I've hit a snag trying to integrate js libraries into my project. Would greatly appreciate any assistance! By the way, I attempted adding the following code to my main.js file but it didn't have th ...

Activate the default JavaScript action within an event handler

I need help understanding how to initiate the default action before another process takes place. More specifically, when utilizing a third-party library and applying an event handler that triggers one of their functions, it seems to interfere with the defa ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

Is there a way to capture all ajax responses?

Is it possible to capture all responses from an ajax request, regardless of the library being used such as jQuery, prototype, or just the vanilla XMLHttpRequest object? I am looking for a way to append to any existing handler without removing it. Thank y ...

reactjs error: Attempting to utilize the toLowerCase method on an undefined property during double mapping

My issue involves a JSON structure that requires mapping a function twice in a loop to access objects within an array. Once mapped, I need a textbox for searching the data list. However, I am encountering the following error: TypeError: Cannot read proper ...

Following the execution of the "ng build --prod" command in Angular 2, the functionality of ui

Utilizing an Angular program with a Node.js server and the ng serve command has been successful. However, when attempting to transfer this code to a shared Linux server and using XAMPP for compilation, an error was encountered: ng build --prod The error ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Initialization issue detected in Angular's module APP_INITIALIZER

In my auth module, I have implemented a mechanism to import and set up MSAL configuration before initializing the app. I am using APP_INITIALIZER to delay the initialization of the app until the configuration for MSAL-ANGULAR is retrieved. The issue I am f ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

My HTML grid table is not being properly rendered by the JSON data

I'm currently facing a challenge with rendering my HTML grid table in Angular using JSON data retrieved from a MySQL database. I would greatly appreciate any assistance or guidance on how to solve this issue. View the output of the Angular code here ...