Running an interval in Angular 2 only once on component initialization

In my component, there is a recurring interval set up:

export class FoobarComponent implements OnInit {

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        setInterval(() => { console.log('Hi'); }, 1000);
    }    
}

Every time the component is called, a new interval is created, adding to the existing ones.

I attempted to use an ID (similar to what I used to do with plain JS) like this:

export class FoobarComponent implements OnInit {

    intervalId: Number;

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        if(this.intervalId) { // always undefined 
            window.clearInterval(this.intervalId);
        }
        this.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
    }
}

However, this approach doesn't work because intervalId becomes undefined each time the component is called. Thus, old intervals continue running while new ones are added.

I'm unsure how to stop a currently running interval. Can you assist me with this?

Answer №1

To ensure all instances of the class can access the same intervalID, you can make it static.

export class FoobarComponent implements OnInit {

    static intervalId: Number;

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        if(FoobarComponent.intervalId) { // always undefined 
            window.clearInterval(this.intervalId);
        }
        FoobarComponent.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
    }
}

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

Having trouble with this.$.... not functioning properly post migration from Vue2 to Vue3

Recently, I began the migration process using the migration guide and the Compat build to ensure a smoother transition. Here is how I have configured the vue.config.js: chainWebpack: (config) => { // Set alias for Vue compatibility build config.resolve. ...

Tips for defining a state variable as a specific Type in Typescript

I am working with the following type: export type AVAILABLE_API_STATUS = | "Created" | "Process" | "Analysis" | "Refused"; I am wondering how to create a state using this type. I attempted the following: co ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

What is the easiest way to incorporate a basic dialogue box in my Angular 7 application?

In an Angular 7 app, I am retrieving data from an API and displaying it in a table. The table includes a button at the end of each row that triggers a function to log the row's data to the console. Below is the code snippet for this functionality: Wi ...

In TypeScript, the error "Property does not exist on type 'any[]'" indicates that a specific property is not recognized on

Working on my project using Textscript in Next Js has been mostly smooth sailing, but I keep encountering warnings in my script that say 'Property does not exist on type any[ ]'. The red line under the name, image, and price properties is a sourc ...

Display the chosen HTML template in real-time

Recently, I started using Angular 2 and encountered an issue that I need help with. 1] I have created 2-3 templates for emails and SMS that will display predefined data. 2] I have also designed a screen with a dropdown menu containing options like email ...

React Error: Unable to access property 'getBoundingClientRect' because it is undefined

server: Node.js, MongoDB, Graphql front-end: React --typescript, apollo-client, Graphql I believe the issue lies in the timing or sequencing of data retrieval and rendering. However, I'm struggling to find a solution to this problem. Error Uncaug ...

Display a button in ngx-datatable on mouse hover in Angular 9

My goal is to display a link on mouseover of the corresponding cell in ngx-datatable. However, the link appears on all rows within that column instead. Below is the code I am currently using: <ngx-datatable class="material ml-0 mr-0" [r ...

Caution in NEXTJS: Make sure the server HTML includes a corresponding <div> within a <div> tag

Struggling with a warning while rendering pages in my Next.js and MUI project. Here's the code, any insights on how to resolve this would be greatly appreciated! import "../styles/globals.scss"; import { AppProps } from "next/app"; ...

Angular 7 CLI throwing an error when generating a component: 'Unable to locate property 'sourceRoot' due to undefined value'

Encountered this error while attempting to run the command in CLI: ng generate component [component-name] An error kept popping up: Cannot read property 'sourceRoot' of undefined It seems like the error started happening after I updated my An ...

Watching for when the state changes in the AngularJS framework using the `$scope.$on('$stateChangeStart')` and

My AngularJs application has the functionality to detect a change in state (using ui.router) and prompt the user to save any unsaved changes. Currently, I am utilizing a confirm dialog for this task: $scope.$on('$stateChangeStart', () => { ...

Does Vetur have additional undefined types in the type inference of deconstructed props?

When reviewing the code below, Vetur concluded that x,y are of type number | undefined. The presence of undefined is leading to numerous warnings when using x,y further in the code. Is there a way to eliminate the undefined from the type inference? <s ...

Unexpected artifacts are being introduced to the build folder by the compiler

Currently, I am following the steps outlined in this Getting Started guide to set up the installation of tsoa. According to their instructions, I have created a routes.ts folder and placed it under /build: /build /routes.ts Next, in /src/app.tsx, I mak ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Avoid utilizing the i18n angular tool to translate any individual words within the string

For my internationalization application, I am using i18n angular. I am trying to figure out how to translate a string while keeping one word in the middle intact. This word might be an abbreviation or the name of a company. For example, when translatin ...

Utilizing Electron's BrowserWindow in a React Typescript Project: A Comprehensive Guide

I am currently exploring ways to incorporate third-party URLs like Disney+ or Spotify into my application. Unfortunately, using iframe is not feasible due to many sites blocking it. My initial thought was to utilize Electron's webview tag, but this op ...

Unable to access GraphQL endpoint through Apollo in Angular

I have encountered an issue while using Angular 15 and attempting to query a GraphQL endpoint with Apollo. After running ng add apollo-angular, all dependencies and imports were taken care of, the uri of the endpoint and correct version of GraphQL were spe ...

The two-way binding does not connect the property and event halves to the same target

I am trying to create a two-way binding using reactive forms in Angular. I need to exchange data between the child component and the parent component seamlessly. This is the HTML code for my child component: <input type="text" #name class=&qu ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...