Stopping $interval using promise after a specific condition is satisfied using Angular timer

I'm struggling to figure out why my $interval service isn't canceling properly. It seems like something important is missing.

In my code, I've set up a counter that's tied to a counting property: $scope.sessionCounter


$scope.sessionCounter = 5;

var intializeSessionCounter = function () {
    $scope.sessionTime();
    $interval(function () {
        $scope.sessionCounter--;
        if ($scope.sessionCounter > 1) {
            console.log('timedown', $scope.sessionCounter);
        }
        else {
            $scope.showSessionTimeoutWarningModal();
            $scope.stop();
        }
    }, 1000);
}
intializeSessionCounter();

Everything works fine until it reaches the if statement and eventually hits the else statement when $scope.sessionCounter becomes 1. The modal opens as intended, and then $scope.stop is called with $interval.cancel(null) to stop the interval from running. However, for some reason, the interval doesn't cancel and the modal keeps reopening because the $interval continues even after reaching negative numbers.


$scope.stop = function () {
    $interval.cancel(null);
}

Answer №1

To ensure proper functionality, you need to assign the $interval provider to a variable.

Consider implementing this code snippet:

$scope.sessionCounter = 5;

var initializeSessionCounter = function () {
      $scope.sessionTime();
      $scope.interval = $interval(function () {
          $scope.sessionCounter--;
          if ($scope.sessionCounter > 1) {
              console.log('timedown', $scope.sessionCounter);
          }
          else {
              $scope.showSessionTimeoutWarningModal();
              $scope.stop();
          }
      }, 1000);
}
initializeSessionCounter();

... 
$scope.stop = function () {
    if( $scope.interval !== undefined){
        $interval.cancel($scope.interval);
        $scope.interval = undefined;
    }        

}

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

working with received data from a JavaScript object

Looking for code assistance, I have a data object serving as my data source. var data = [ { "label":"May 7", "value":25736.6, "proID":"ISB" }, // more data objects... ]; I'm manipulating this data to generate another ...

Could anyone please provide advice on how to resolve the issue I encountered when trying to make Post and get Http method calls using protractor?

I am currently facing an issue while trying to make a GET API request using protractor. The challenge lies in using the bearer token generated from a previous POST response in the headers of the GET request. Although I have successfully executed the POST r ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

Issue encountered while attempting to include a background image in React JS

I encountered an issue when attempting to include a background image in react js. ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Unable to locate module: An attem ...

Is there a way to disable default tooltips from appearing when hovering over SVG elements?

Looking for a way to display an interactive SVG image on an HTML page without default tooltips interfering. While I'm not well-versed in javascript/jQuery, I've managed to implement customized tooltips using PowerTip plugin. However, these custom ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Tips for sending a Postgres Pool or Client over a socket

After deploying my server to Heroku, I encountered an issue with sending a request to my Raspberry Pi for running a scraping function and updating a table in the Heroku Postgres database. The problem seems to be related to the client.query() function not b ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Extracting the URL of the @font-face declaration in CSS with the use of JavaScript

Currently, my CSS file contains numerous @font-face tags. Each tag specifies a unique font-family and src URL. @font-face{ font-family: Garamond; src: url('ePrintFonts/pcl_91545.ttf'); } @font-face{ font-family: C ...

What is the process for incorporating an npm package into an HTML document?

Here is the code from my HTML file: <!DOCTYPE html> <head> ... </head> <body> ... <script src="script.js"></script> </body> This is what I have in my JavaScript file named script.js: import * as File ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

When a user accesses a page, the UI-router shows the raw code in the UI-views

I am a newcomer to utilizing ui-router and I am facing challenges with managing routing and reloading some states. Any assistance would be greatly appreciated. An overview of my index.html <html ng-app="resApp"> <head></head> < ...

Is the Javascript framework malfunctioning even though the code is identical to the one on jsfiddle

<html> <head> <meta charset="UTF-8"> <title>Interactive Globe Display using iTowns</title> <style> html { height: 100%; } body { margin: 0; overflow: hidden; ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

Prevent the Spread of an Event for a Particular Controller

tl;dr Summary Develop a function that is able to handle a specific event on multiple elements within a hierarchy. The function should execute when the event is triggered on the first element reached during bubbling, but should not continue executing or re ...

Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success. Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of re ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...