Having trouble with the clearInterval() method in Angular 6 to stop the refresh functionality?

Incorporating a Refresh Functionality on a page that offers users two options: Refresh Buttons

  1. Clicking the Refresh button to refresh the page (straightforward)

  2. Allowing users to set a Refresh Frequency (option to automatically refresh the page at specific intervals) Set Interval Refresh

The different intervals, displayed in the image, are stored in an object like this:

timer: RefreshTimer[] = [
{value: 15000, time: '15 Sec'},
{value: 30000, time: '30 Sec'},
{value: 45000, time: '45 Sec'},
{value: 100000, time: '1 min'},
{value: null, time: 'Cancel'}];

I am utilizing setInterval() to call the refresh() method as shown below:

refresh() {
this.router.navigateByUrl('./views/refresh/', { skipLocationChange: true }).then(() => {
  console.log(decodeURI(this.location.path()));
  this.router.navigate([decodeURI(this.location.path())]);
});}

refreshFrequency(time) {
     if(time === null){
        this.counter = 110;
     }
this.progressInterval = setInterval(() => {
  this.counter += 10;
  this.refresh();
  console.log('this.counter', this.counter);

  if(this.counter >= 100){
    clearInterval(this.progressInterval);
    console.log('cleaned and finished');
  }
},time);

}

Invoking setInterval() as follows:

<mat-form-field class="timer" style="width: 10px;">
           <i class="far fa-clock"></i>
           <mat-select class="alarm-dropdown" trigger="alarmTrigger" #alarmSelect>
           <mat-option   *ngFor="let time of timer" 
                  (click)="refreshFrequency(time.value)" 
                  [value]="time.value">
              {{time.time}}
            </mat-option>
            </mat-select>
 </mat-form-field>

The current behavior is that clearInterval() does not work after selecting "Cancel" from the dropdown.
1. Step 1
2. Step 2
3. Step 3

Thank you for the assistance.

Edit: Here is the SlackBitz for it.

Answer №1

Using timers can be beneficial, but they have a tendency to go haywire, so proceed with caution. It's important to manage your timers effectively by not creating more than necessary and keeping track of the ones you've already set up.

Here's a useful approach:

this.timerReference = null;

Organize your code for initiating and stopping the timer. Ensure that only one timer is active at a time to prevent confusion.

refreshTiming(duration) {
    if (!this.timerReference && duration !== null) {
        console.log('Setting up a timer. It will run every ' + (duration / 1000) +  ' seconds');
        this.timerReference = setInterval(() => {
            this.counter += 10;
            this.refresh();
            console.log('Current count:', this.counter);
            if (this.counter >= 100) {
                clearInterval(this.timerReference);
                console.log('Timer has finished running as scheduled');
                this.timerReference = null;
            }
        }, duration);
    } else if (duration === null && this.timerReference) {
        console.log('Stopping the timer prematurely.');
        clearInterval(this.timerReference);
    }
}

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

Integrating Solace Node.js API with Webpack

I am currently working on an Angular2 TypeScript web application that has been built using webpack. My goal is to integrate solclientjs into the project, but I keep encountering the error displayed below: solclientjs-exports.js:34 Uncaught Error: Cannot f ...

Tips for avoiding incorrect type assignments in TypeScript

As a new TypeScript user, I'm looking for ways to prevent incorrect types from creeping into my data structures. I was surprised that TypeScript did not restrict the assignment of this.myString = myArgument, even though the type of myArgument is unkno ...

Utilizing Material UI and TypeScript to effectively pass custom properties to styled components

Currently, I am utilizing TypeScript(v4.2.3) along with Material UI(v4.11.3), and my objective is to pass custom props to the styled component. import React from 'react'; import { IconButton, styled, } from '@material-ui/core'; con ...

Launching Angular 2 Application on Azure Cloud

I have recently been diving into the world of Angular 2 and Azure. Following the steps outlined in the Angular 2 Tutorial, I was able to successfully run my application locally without any issues. After deploying the app to Azure, I encountered a problem. ...

Steps for personalizing the dataset on a PrimeNG bar graph

I'm currently working with primeng in an Angular project and I need to create a bar chart where the last two horizontal bars have different colors. Right now, the last two bars are incorrectly being assigned to represent dogs and cats. My goal is to ...

Utilize mapGetter and mapMutations in Vuex with TypeScript without the need for class-style components syntax

After completing a project in Vue, I found myself getting a bit confused without static types. To address this, I decided to incorporate TypeScript into my project while still maintaining the traditional way of writing code, without classes and decorators. ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

The art of effectively overloading functions within TypeScript interfaces

I have the following interface definition: interface foo1 { add(num1: number, num2: number): number; subtract(num1: number, num2: number): number; } Next, I instantiate an object in the shape of foo1: let myFoo1: foo1; myFoo1.add(5, 6); // OK m ...

Angular allows for the dynamic inclusion and exclusion of components, providing a flexible

In my setup, I have a container that houses two distinct components. The first component receives a list of users from the backend. Upon clicking on a specific user, I aim to display all of their detailed information in the main container of the second co ...

Re-subscribe to an Observable that has been unsubscribed in RxJS

Utilizing a Service to periodically "ping" my server every 2.5 seconds, I am able to retrieve the response time from the server by using observables. My implementation also involves angular 2 and typescript. Now, I am facing an issue where I want to be a ...

Learn the process of transferring a complete JSON object into another object using Angular

I'm having trouble inserting one object into another. My JSON object is multidimensional, like this: { "item1":{ "key":"Value", "key":"Value" }, "item2":{ "key ...

Is there a way to retrieve the status code from the HttpClient module in Angular?

Can you find out how to retrieve the status codes for all requests using the HttpClient method? callingAPI() { let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'application/json'); headers = headers. ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

Exploring the potential of utilizing dynamic types in a TypeScript React application alongside React Hook Form

Currently, I am in the process of converting a React application that was previously not using TypeScript to now incorporate TypeScript. I am facing an issue with the use of React Hook Form's setValue method. The component I am working on serves as a ...

Synchronizing Events across Two JavaScript Applications

In my game app (using Electron) and web app (testing on Android Chrome), they communicate through a websocket server to coordinate a countdown. I've noticed that in environments with low latency, the synchronization is fine. However, when there is mor ...

Get data from an Angular 12 hyperlink

Here is the link to my questionnaire: http://localhost:4200/EditQuestionnaire;id=1;name=Random%20Questionnaire I have included this code in the ngOnInit() function, however, I am having trouble retrieving the values: ngOnInit(): void { this.ro ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Unable to inherit a base class in NodeJS using Mongoose and Typescript

Currently, I am trying to utilize Mongoose 4.5.4 and its associated typings in a NodeJS environment with Typescript, all the while implementing the Repository Pattern. RepositoryBase: export class RepositoryBase<T extends mongoose.Document> imp ...

Create a definition for the keys type of an object based on an array

I am looking for a way to dynamically assign symbols from an array called TYPES_ARR as keys in the variable TYPES_GENERATED. I want each key in TYPES_GENERATED to have a corresponding symbol value. const TYPES_ARR = [ 'HttpClient', 'Par ...