Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be greatly appreciated.

Here is the code for my component -

export class AppComponent {
  counter=0;
  progressInterval;

  ngOnInit(){
    this.progressInterval=setInterval(() => {
      this.counter=this.counter + 10;
      if(this.counter >= 100){        
          clearInterval(this.progressInterval);
      }
    },200);
  }
}

Below is the HTML code for my component -

<p style="margin:20px;">
    <ngb-progressbar
      type="warning"
      [value]="counter"
      [striped]="true"
      [animated]="true"
    >{{counter}}</ngb-progressbar>
  </p>

This screenshot displays the progress bar in action:

Screenshot

Thank you!

Answer №1

Resolved the issue by importing "clearInterval" from the "timers" module, which I had forgotten to do initially. Updated my code as shown below and now it is functioning correctly.

import { 
  setInterval,
  clearInterval
} from 'timers';

Appreciate everyone's assistance with this problem.

Thank you

Answer №2

Another option is to store the interval in a variable. For example:

ngOnInit() {
    const interval = setInterval( () => {
      this.counter += 10;
      if ( this.counter >= 100 ){        
          clearInterval( interval );
      }
    }, 200);
  }

Answer №3

Experimented with ES6 modules in Chrome 61 and later versions.

<script type="module">
  class MyComponent {
    constructor() {
      this.counter = 0;
      this.progressInterval;
    }

    initialize() {
      this.progressInterval = setInterval(() => {
        this.counter += 10;
        console.log('this.counter', this.counter);

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

  const element = new MyComponent();
   
  element.initialize();
</script>

Your code using ES6 syntax is functioning flawlessly. There may be a different outcome when using Angular5, see this response:

Angular 2 setinterval() keep running on other component

Answer №4

The reason for this limitation is that the variable scope is restricted to the current function only, and the interval function has its own 'this' variable which cannot access the 'this.progressInterval' variable.

You can try implementing it in the following way:

ngOnInit(){

    const initScope = this;
    this.progressInterval=setInterval(()=>{
      initScope.counter=initScope.counter+10;
      if(initScope.counter>=100){        
          clearInterval(initScope.progressInterval);
      }
    },200);
  }

Answer №5

When implementing Interval in Angular, it's important to keep a few things in mind:

  1. Ensure that you only instantiate Interval once. If you navigate away from the component and return before clearing the interval, a second instance may be created while the original continues running.

  2. Always have a fail-safe method for clearing the interval when leaving the page or scope of the component using OnDestroy. Remember to clear or dispose of the interval when it is no longer needed.

import { Component, OnInit, OnDestroy } from '@angular/core';

[..]

export class YourComponent implements OnInit, OnDestroy {

  progressInterval: any;

  ngOnInit() {
    [..]
  }

  ngOnDestroy() {
    if (this.progressInterval) { clearInterval(this.progressInterval); }
  }

}

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

Implement AngularJS to ensure that scripts are only loaded after the page has finished rendering

I am having trouble implementing the TripAdvisor widget on my website. It functions correctly when the page is refreshed, but it does not appear when navigating through links. Additionally, an error message is displayed stating that the document could not ...

Having issues with Jquery and duplicating tables functionality not functioning as expected

I am facing an issue with two external jQuery files. One file allows me to clone the last row of a table, while the other is supposed to retrieve the id of a select tag based on a class assigned to it. However, the second script only works for the original ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

Stubbing out a module's function with Sinon

Let's envision a scenario where there is a file present: // app.js const connection = require('./connection.js') module.exports = function (...args) { return async function (req, res, next) { // code implementation ... const ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

Injecting a useFactory provider in Angular is a common practice

I manage a factory provider service that selects a service based on a flag. Everything works fine when I need a debug students service, but when I set the flag to false, the application throws an ERROR TypeError: serverService.fetchData is not a function. ...

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

Angular 8 allows for the utilization of Ul li elements to create an expandable and collapsible hierarchical

As a newcomer to Angular, I have managed to code a representation of hierarchical JSON data in a tree view using recursive calls. The code works well, but I am faced with the challenge of implementing an expand and collapse functionality for the treeView u ...

What is the best way to insert a JavaScript variable into a filter while using ng-repeat?

I'm currently working on a situation where I have the following code: <div ng-repeat="i in MediaFeedItems | filter: { category: 'userSelect' }" class="mediafeed--item"> This specific code snippet is responsible for iterating through ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

I seem to be experiencing difficulty receiving the JavaScript alert on my controller page

In my ActionResult function, I have the following code: public ActionResult Copy( int bvVariableid ) { var iReturn = _bvRepository.CopyBenefitVariable( bvVariableid, CurrentHealthPlanId, CurrentControlPlanId, _bvRepository.GetSecInfo( ).UserId ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

Injecting a controller into an AngularJS module within an anonymous function

As a newcomer to the world of javascript and just beginning to work with angular.js, I have a question. I'm wondering if there is a method for injecting a controller into a module that is declared within an anonymous function. This is how my code cu ...

Dynamic routes in NextJS automatically append a .txt extension to the end of the URL

Issue: When using NextJS, the link <Link href="/link">link</Link> redirects to /link.txt For a simple link like this, HTML <a href="/link">link</a> can be used instead The real problem arises when using NextJS ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

The 'filter' property is not found on the 'Observable<>' type

enter your code here... searchHospitals(term: string = null): Observable<Hospitals[]> { let hospitalsList = this.getHospitalsData(); if (term) { hospitalsList = hospitalsList.filter(hospital => hospital.name.toLocaleLowerCase() ...

Prevent unnecessary requests for asset images in Angular 5

Within my Angular application (running version 5.1.0, built with angular-cli and webpack), I have a country selector component that allows users to choose a country from a drop-down menu or by typing the name in an autocomplete field. Each matching result ...

MongoDB and Node.js encounter unexpected outcomes due to undefined variables

I am trying to retrieve data from my collection called students within the pool database in MongoDB. Despite having a successful connection to the database, when I use console.log(result.lastname), it returns undefined. Below is an excerpt from my server ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...