Creating a countdown clock in Angular 5

I am currently working with Angular 5.

Is there a way to initiate a timer as soon as the 'play' button is clicked, in order to track the elapsed time since the click?

Additionally, I am interested in learning if it's feasible to pause the timer and then resume from where it was paused.

After some trial and error, I found a solution based on Pardeep Jain's response. Though it wasn't exactly what I had in mind. Instead of a countdown, I needed to track the duration. Below is the code snippet that resolved my issue:

time: number = 0;
interval;

startTimer() {
  this.play = true;
  this.interval = setInterval(() => {
    this.time++;
  },1000)
}

pauseTimer() {
  this.play = false;
  clearInterval(this.interval);
}

Answer №1

To create a timer in Angular, you can use the setInterval function. Here is an example code snippet:

timeLeft: number = 60;
interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
}

pauseTimer() {
    clearInterval(this.interval);
}
    
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left...</p>

#Working Example

#Another way to create a timer is by using Observable timer as shown below:

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
}

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information, you can visit this link

Answer №2

If you're in need of a more robust solution, consider checking out the npm package known as marky. This tool goes beyond basic timing functionalities and offers additional features to enhance your time tracking experience. To get started, simply install the package using npm and import it into your project wherever necessary. For more information about the marky package, visit: https://www.npmjs.com/package/marky

Once installed via npm, you can utilize marky like this:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

The key parameter serves as a unique identifier for each time measurement. By assigning different keys, you can track multiple timings and later refer back to them for analysis.

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

Tips for receiving a linter/compiler warning when comparing a function without its call being made?

Often, I find myself making a common mistake when writing TypeScript code: class Foo { constructor() { } public get isFoo(): boolean { return true; } // getter public isBar(): boolean { return false; } // normal function } let foo = new Foo(); if ( ...

It is not possible to repeatedly hear the same event on a single element

It seems that I am unable to listen to an event multiple times on a single element. Upon investigation, I have found the following observations: This issue arises when triggering an RxJS observable from lifecycle methods such as ngAfterViewChecked, ngDoC ...

Unusual conduct exhibited by a 16th version Angular module?

I've created a unique component using Angular 16. It's responsible for displaying a red div with a message inside. import { ChangeDetectionStrategy, Component, Input, OnInit, } from "@angular/core"; import { MaintenanceMessage } ...

Troubleshooting problems with permissions when using the AWS IAM assumeRole function with session

Within my aws-cdk application, I am working on setting up a lambda function to assume a specific role and obtain credentials through aws-sts. These credentials need to include a tenant_id tag. AWS CDK Code: Role to be assumed: const pdfUserRole = new Rol ...

Tips for optimizing HttpRequests within nested for-loops that utilize subscribe()?

Our REST-API is designed to be frontend agnostic, meaning it always sends the IRI to nested resources. This results in multiple HTTP calls needed to retrieve data; first for the parent resource, then its child resources and so on. Each Country has linked E ...

What steps should I take to resolve the error message "ESLint encountered an issue determining the plugin '@typescript-eslint' uniquely"?

Struggling to enable eslint linting in an ASP.NET Core MVC project that incorporates React.js and typescript? I'm facing a tough challenge trying to resolve the error mentioned above. In my setup, I'm using Visual Studio 2022 Community Edition 1 ...

Rule in ESLint mandating return type for arrow functions

I currently have the following arrow function within my Angular project: this.httpClient.get('url').subscribe((response)=>{ }); It is important to note that ESLint should detect an error in the above code due to not specifying a return type. ...

Angular application making a POST request to a Spring REST API

I have developed a RESTful API using Spring Boot and a client application using Angular 4. Both applications are currently running locally. When testing the POST method with Postman, it functions correctly. However, when attempting to make a POST request f ...

The Angular form remains invalid despite all form fields being valid

After spending hours on an Angular form validation project, I have encountered an issue that has been difficult to resolve. The form I created seems to be working fine based on a demo I shared, where it shows the form status as VALID. However, when running ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Optimal method for passing data from a function that utilizes a callback

My service involves calling a method with a callback: import {someDataBaseFunction} from 'something/somthing'; class MyService{ myServiceFunction(param1, param2){ someDataBaseFunction(param1, param2, (error) => { if ( ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

Ways to verify if a certain type possesses an index signature during runtime

Is it possible to create a type guard in JavaScript that checks if a given type implements an index signature? I'm unsure if this concept would be viable, but here is the idea: I am looking for guidance on how to implement the logic within this funct ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

Using class variance authority variants allows for the acceptance of a "null" value, although it is not recommended

My approach with cva is as follows: const checkboxOptions = cva('border ...', { variants: { size: { sm: 'h-4 w-4', md: 'h-5 w-5', lg: 'h-6 w-6', }, }, defaultVariants: ...

Creating Beautiful MDX Layouts with Chakra UI

Currently, I am attempting to customize markdown files using Chakra UI within a next.js application. To achieve this, I have crafted the subsequent MDXComponents.tsx file: import { chakra } from "@chakra-ui/react" const MDXComponents = { p: (p ...

Create distinct projects for WebApi and Angular to keep them separate

Currently, I am working on a project that involves webApi and Angular apps combined in one project by default from Visual Studio. However, I want to separate them into two distinct projects. To achieve this, I removed all the SPA-related code from my StarU ...

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

The issue of flickering while scrolling occurs when transitioning to a new page in Angular

I have encountered an unusual issue in my Angular 13 + Bootstrap 5 application. When accessing a scrollable page on small screen devices, the scrolling function does not work properly and causes the page to flicker. I observed that this problem does not o ...