Tips on incorporating the timer service into your Angular component

What's the best way to implement a timer/countdown feature in a component? Is it advisable to use a service for this purpose?

import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';

export class IntervalRunnerOptions {
    constructor(
        public callback:()=>void,
        public period:number=1000,
        public initialDelay:number=0,
        public TotalTime: number) {
    }
}

export class IntervalRunner {
    subscription: Subscription = null;

    start(options:IntervalRunnerOptions) {
        if(this.subscription==null) {
            this.subscription = timer(options.initialDelay, options.period).subscribe(result => options.callback());
        }
    }
    
    stop() {
        if(this.subscription!=null) {
            this.subscription.unsubscribe();
            this.subscription = null;
        }
    }
}

Answer №1

Check out this stackblitz demonstration to see how it's done

@Component({
  selector: "my-app",
  template: `
    <button (click)="start()">Start</button>
    <button (click)="stop()">Stop</button>
    <p>
      <em>{{ message }}</em>
    </p>
  `
})
export class AppComponent {
  message: string;
  constructor(private runner: IntervalRunner) {}

  start() {
    this.runner.start(
      new IntervalRunnerOptions(e => (this.message = "Hi: " + e), 1000, 0, 5)
    );
  }

  stop() {
    this.runner.stop();
  }
}

I've updated the callback function to include an argument

public callback: (e: any) => void
, which will receive the timer result.

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 steps can I take to prevent receiving the error message "Certain components in XXX are not associated with the entity" in Strapi?

User I am facing an issue with my application's endpoint for adding a like to a post. The endpoint is supposed to receive the user id who liked the post and insert it, along with the number of likes (not crucial at this moment), into a database. To ac ...

Looking to organize, refine, and establish a default value with the help of rxjs

In my Angular application, I have an observable that is linked to a reactive forms dropdown control. My goal is to filter, sort, and display the default value. I've created two separate implementations - one for filtering and sorting without displayin ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Whenever I try to run ionic serve, an error pops up saying: "typescript: node_modules/@types/node/worker_threads.d.ts, line: 8 '=' expected."

My Ionic Info: cli packages: (/usr/local/lib/node_modules) @ionic/cli-utils : 1.9.0 ionic (Ionic CLI) : 3.9.0 Global Packages: Cordova CLI : 9.0.0 (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8f839e88839a8dc180858eacd5c2 ...

What could be causing Typescript Compile Errors to occur during runtime?

In the Visual Studio React + Redux template project, I have created a react component with the following "render()" method: public render() { return ( <React.Fragment> <h1>Welcome to the Adventure Company {th ...

Having a problem where the Next.js project is functioning in development mode, but encountering a "module not found" error

After following multiple tutorials to integrate Typescript into my existing app, I finally got it running smoothly in dev mode using cross-env NODE_ENV=development ts-node-script ./server/index.js However, when I execute next build, it completes successfu ...

Does an AsyncMethod().Result equivalent exist in typescript?

When working in C#, you have the ability to call the result of an asynchronous method synchronously by accessing the Result property. For example: var returnVal = AsyncMethod().Result; What is a similar approach in typescript? ...

Error: unable to locate module that was imported from

Every time I try to run the project using this command, an error pops up: > npm run build npm info using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a9b7aa87fee9f1e9f0">[email protected]</a> npm info using ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Troubleshooting issues with Angular 2 HTTP post and Web API integration

Here is an example of my Web Api Core Controller Method: public void Post(Sample sample) { _sampleService.CreateSample(sample); } The Sample POCO is defined as follows: public class Sample : BaseEntity { public string BarCode { get; s ...

The assignment to 'total' is prohibited as it is either a constant or a property that is read-only within the get total() function

After running the command ng build --prod in my project, I encountered the following error message: "Cannot assign to 'total' because it is a constant or read-only property for function get total(){}" The function causing the issue is: get to ...

What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...

Leveraging conditional types and optional variables in Typescript to translate a string into another form

Visit Playground I have been experimenting with creating a versatile function that can map one string to another during the compilation phase. The idea is simple - if a string is provided as input, it should return "data", and if the input is undefined, i ...

FIXED-IONIC 3: The 'questions' property is missing from the 'Object' type

Encountering an issue with a single line of code and exhausted all resources in attempts to resolve it. Seeking assistance for my simple quiz, disregarding the current data presentation. The trouble arises within my data.ts file, specifically at one parti ...

Unable to locate the proper way to manage angular version 13.0.0 using TypeScript

I have set up my angular form correctly, but I am still encountering an error. The following errors are shown: Cannot find control with path: 'builderPreferences -> idx -> groupId' Cannot find control with path: 'builderPrefe ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

Encountering the 'Default setting for timestampsInSnapshots now set to true' error in Firestore console

Encountering a Firestore error in the console while using Angular. @firebase/firestore: Firestore (5.8.3): The timestampsInSnapshots setting now defaults to true and does not require explicit setting. It is advised to remove it from firestore.settings( ...