Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route change?

setInterval(() => {
    ...
}, 10000);

Answer №1

To stop the interval in this particular situation, you can utilize a hook. In my case, I manage it within the component/view structure.

export class TestInterval implements OnInit, OnDestroy {
     public timerInterval: any;
     ngOnInit() {
       // The interval scope needs to be accessible within the component for clearing it upon component destruction.
       this.timerInterval = setInterval(function(){...}, 10000);
     }
     ngOnDestroy() {
        // This will clear the interval when the component is no longer needed, like when navigating away from a route.
        clearInterval(this.timerInterval);
     }
}

Answer №2

Here's the solution:

activateRouter() {
  this.timer = setInterval(()=>{
                ...
            }, 10000);
}

deactivateRouter() {
  clearInterval(this.timer);
}

Answer №3

Consider using the OnDeactivate feature from the angular2/router library (and possibly also OnActivate based on your specific needs) for managing the timer when a user navigates away from the current route.

export Compnent implements OnInit, OnDeactivate {
    private timer;

    ngOnInit(){
        this.timer = setInterval(_ => {
            // perform actions
        }, 10000);
    }

    routerOnDeactivate() {
        clearInterval(this.timer);
    }
}

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

Removing data with the click of a button

I have successfully implemented a feature where clicking the "add to my stay" button displays the name and price data. Subsequently, it automatically changes to a remove button when clicked again for another addon. If I press the remove button of the first ...

The notify.js fails to display notifications in the event of an error

Why am I not receiving any error notifications even when there is an error message in the response object? $.ajax(settings).done(function (response) { if ( "error_message" in response ) { console.log(response); $.notify(" ...

Issue: Module 'serialize-javascript' not found despite being present in the 'node_modules' directory after executing npm start command in ReactJS project

My npm start suddenly stopped working. This issue arose after I switched to an unused branch with unrelated histories, made some changes, pushed them (unaware that the branch was outdated), then used git checkout -f "" to go back to the recent br ...

What could be causing the Twitter Timeline to fail to load based on a variable in a Vue.js component?

My goal is to display the Twitter timeline of multiple accounts based on the route. I initially attempted to use a plugin called vue-tweet-embed, but encountered issues with it. As a result, I resorted to the traditional method by embedding twitter's ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

Why does React component still use old state when re-rendering?

I recently encountered an issue with my code. I am using an array of objects in my state, and when I delete an item from the array, the component does not render correctly without the deleted object. Additionally, when I try to open another object (trigger ...

Use an if statement in Angular to conditionally add a title attribute with an empty value to HTML

How can I conditionally add the title attribute to a div without creating another div and using ngIf? If the permission is true, I want to include a title in my div. Here's what my current div looks like: <div (click)="goToChangelog()&quo ...

What is the most effective method for postponing the loading of JavaScript?

Incorporating a bootstrap theme into my project has required me to include several javascript files. The challenge arises when some pages load dynamic content from the server, resulting in the entire HTML not being present when the javascript files are exe ...

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Is there a way for me to retrieve dynamic text?

I used an "IF" statement to display dynamic text - if it's null, show something, otherwise show something else. However, I am getting a blank result. What did I do wrong? <View style={styles.rightContainer}> { () =>{ if(t ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

ReactJS encountering issue with sending POST request, blocked by CORS preflight options

Every time I try to send a POST request to the server, it always responds with an unexpected OPTIONS. My login application built with React and Apollo is experiencing issues. Upon form submission, a mutation should be sent to the server via a POST request ...

Create a JavaScript and jQuery script that will conceal specific div elements when a user clicks on them

Within my navigation div, there exists another div called login. Through the use of JavaScript, I have implemented a functionality that reveals additional divs such as login_name_field, login_pw_field, register_btn, do_login_btn, and hide_login upon clicki ...

Display a pop-up window when hovering over a table cell using HTML and JavaScript

I am currently developing a JavaScript application and came across a helpful library called qtip2. My objective is to have different information displayed when the user hovers over each cell in the table. The qtip2 library I mentioned earlier can display ...

Updating the innerHTML of a button with a specific id using Javascript is not possible due to it being "null."

My objective is to create a button that, when clicked, triggers a function to alter the styling of the HTML tag as well as the text or innerHTML of the button itself. Sounds simple enough, right? Unfortunately... The HTML: <!DOCTYPE html> <html& ...

"Glowing orbs in the night: a dark mode spectacle with

I have implemented a night mode (or perhaps dark mode) toggle button located at the top-right corner of my webpage. Here is a link to a perfect example showcasing what I am aiming for However, unlike the provided link, I switch between night mode and lig ...

Determine the shared elements within a single array by utilizing Javascript

I have the following array of mergeUniqueItems: var mergeUniqueItems = ["-JsDEcxz_ZSGFLKwd1QM", "-JsJ2NXGDYKI6QRsuXVK", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2YLPiP6751zh8geS"] After using this code snippet, I encountered an issue: ...

Is anyone able to assist with resolving the problem of `tsc` constantly monitoring `node_modules`?

Using the Expo platform has been a great experience for me. Here is a snippet from my tsconfig.json: { "compilerOptions": { "paths": { "@/*": [ "./src/*" ], ...

Error encountered while using the getJSON code syntax

Is there an issue with this code snippet? I am receiving a syntax error on line 1: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="http:/ ...

Unfortunately, ng2-datepicker does not currently have support for Angular 4

I am in the process of upgrading from Angular version 2.4.0 to Angular 4, and encountered some peer dependency errors along the way: Attempting to install the latest datepicker component: npm install ng2-datepicker –save Resulted in the following erro ...