The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is displayed along with a timeout redirecting to the home page. However, if the user clicks another link before the timeout completes, they are redirected to a different page while the timeout continues running in the background. After several seconds, the user is still directed back to the home page.

$scope.countdown = 10;
$scope.onTimeout = function() {
  $scope.countdown--;
  timer = $timeout($scope.onTimeout, 1000);

  if ($scope.countdown === 0) {
    $timeout.cancel(timer);
    $location.path('/');
  }
};
var timer = $timeout($scope.onTimeout, 1000);

I am unsure of how to effectively cancel the timer when the user clicks on other links within the page.

Answer №1

To ensure you catch AngularJS's route changes, pay attention to the $locationChangeStart event:

$scope.$on('$locationChangeStart', function () {
    $timeout.clearInterval(timer);
});

This method ensures that when the route is altered, the timer is stopped and the user remains on the same page.

Answer №2

module.controller("TestController", function($scope, $timeout) {

    var onTimeout = function() {
        // do something
    };
    var timer = $timeout(onTimeout, 1000);

    $scope.$on("$destroy", function() {
        if (timer) {
            $timeout.cancel(timer);
        }
    });
});

Make sure to invoke it before the scope is destroyed.

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 updating the dropdown value in a React child component

There are two main components in my code: App component: class App extends Component { constructor(props) { super(props); this.state = { selectedScale: "WholeTone" }; this.handleScaleSelect = this.handleScaleSelect.bind(this); } ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

Calculating the volume of an STL file mesh using three.js

I'm currently trying to figure out how to determine the volume of an STL file. I've successfully managed to obtain the dimensions of the model using var box = new THREE.Box3().setFromObject( mesh ); var sizes = box.getSize(); However, when it c ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Error encountered while using jQuery AJAX to fetch SVG file: 'Invalid format'

For a while now, I have been using various SVGs from Inkscape and loading them into a specific container element with the .load method. Recently, I decided to switch things up and use AJAX's .get method instead, primarily because I wanted to prepend t ...

Animation of active chat list items on Whatsapp

Has anyone figured out a simple method to create an animation like the one in Whatsapp? For example, when you are on a chat screen and go back to the chat list, have you noticed how an active element is briefly highlighted in gray (to indicate which chat ...

Refreshing the Title and URL for a Clutter-Free Look

In my coding project, I am utilizing a method for naming objects in MongoDB through the URL and ui-router functionality. "2000-risk-global-domination"/ After updating the object using Angular Resource, I have made sure to adjust the clean name within the ...

New parents, same name D3.JS

Currently utilizing d3.js to visualize a tree structure. When parsing the JSON object containing nameOfNode and NameOfParent, encountering an issue when there are two nodes with the same name. Seeking recommendations on the most effective way to address ...

Unfulfilled Peer Dependency in react

Encountering javascript issues with react. Chrome error message when rendering page: Uncaught TypeError: Super expression must either be null or a function, not undefined at _inherits (application.js:16301) at application.js:16310 at Object.232.prop-types ...

Utilizing the Vue feature of dynamic route naming within a component's function

Currently, I am working on creating a dynamic view rendering using Vue and Laravel. However, I am facing difficulty in understanding how to pass the dynamic parameter to the component function. Router.map({ '/cms-admin/:page': { comp ...

Unable to Transmit Authorization Header in Cross-Domain Access Situation

My Node.js server has cross-origin communication enabled, allowing my Vue application to access its API from a different origin where static assets are served. This is achieved by setting the following code in Node.js: res.setHeader('Access-Control-Al ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

Conceal or reveal input elements with a toggle function in jQuery by utilizing

When the user chooses an option from a dropdown list, I want to display or hide different input fields accordingly. I attempted to use toggle with boolean values, but it doesn't seem to be working as expected. I expect that if I send 'true' ...

Why does the loginStatus in Redux become undefined when the component is initially rendered?

Currently diving into Redux and encountering a problem that is new to me as I usually work with React without redux. The issue arises when I attempt to showcase a portion of my state within a component named loginStatus. Despite setting up the state in the ...

"Enhance Your Website with qTip2 Feature to Load Multiple AJAX Sites Simult

I'm currently utilizing the qTip2 library for my project and I've implemented their AJAX retrieval functions following this example: http://jsfiddle.net/L6yq3/1861/. To enhance my query, I have modified their HTML to include multiple links. The ...

Encountering problems when transforming Next.js server components into client components

I've been working on a blog site using next.js. Initially, I had a home page that was a server component, but I wanted to convert it into a client component to add interactivity like pagination. However, after converting the code to a client componen ...

Toggle the selection of a div by clicking a button in AngularJS with a toggle function

I have several div elements on a webpage. Each div contains a button! When the button is clicked for the first time: The border color of the div will change to blue (indicating the div is now selected). The "ok" button will be hidden (leaving only t ...

NodeJS allows for seamless uploading of files

I'm encountering difficulties when trying to upload a file using nodeJS and Angular. I've come across some solutions, but they all involve Ajax which is unfamiliar territory for me. Is there a way to achieve this without using Ajax? Whenever I ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...