The $interval cancellation in AngularJS is not functioning as expected, and neither the onDestroy nor stateChangeSuccess events are working as

Below is a snippet of code I wrote to set up an interval that should be canceled when leaving the state, but it's not working as expected.

var init = function () {
        $translatePartialLoader.addPart("app/bottling/palletTnT/palletTnT.grid");
        $translate.refresh();

        //$scope.disablePaging = false;
        setColumnDefs();
        updateDataGrid();
        getRefreshTimer().then(function () {
            if ($scope.RefreshTime != 0 && !intervalPromise) {                   
                    intervalPromise = $interval(function () {
                        getLaneBufferData(palletTnTService.wrapperFilter);
                    }, $scope.RefreshTime * 1000);
                 }
        });


    }


    var intervalPromise = null;

    $scope.$on('$stateChangeSuccess', function () {
            $interval.cancel(intervalPromise);

    });

The 'init' function is called when the page is first opened. The issue at hand is this:

When we navigate away from this page, the interval continues running in the background even though it should have been canceled. Oddly enough, manually refreshing the page (F5) stops the interval from running properly. I've tried various solutions without success, so any help is appreciated.

Thanks in advance...

By the way, using the '$destroy' method yielded the same results.

Answer №1

It appears that the issue lies in how your code is structured. The $stateChangeSuccess event seems to be placed on the same page as your interval, causing it to not fire as expected due to your $scope being destroyed before the state change occurs. Consider switching to $stateChangeStart for better results.

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

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Retrieving the current location synchronously via navigator.geolocation.getCurrentPosition();

I am having an issue with a function that is supposed to return the latitude and longitude as a string when called. Despite providing the correct values for latitude and longitude when alerting, it returns undefined. I would greatly appreciate any assist ...

How to design a dictionary schema using Mongoose

I have been attempting to save a dictionary of objects using Mongoose. Upon realizing that the change detection for saving is lost when using the Mixed type, I am looking for a way to create a schema that does not rely on the Mixed type. While there are m ...

The functionality of .bind() is malfunctioning on both Microsoft Edge and Google Chrome browsers

Everything seems to be running smoothly on Mozilla (version 103.0), but unfortunately, it's not performing as expected on Chrome or Microsoft Edge. $('#loading').bind('ajaxStart', function () { $(this).show(); }).bind('ajaxS ...

Google Chrome does not support inlined sources when it comes to source maps

Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...

How can I use AngularJS to show a JSON value in an HTML input without any modifications?

$scope.categories = [ { "advertiser_id": "2", "tier_id": 1, "tier_name": "1", "base_cpm_price": "", "retarget_cpm": "", "gender": "", "location": "", "ageblock1": "", "ageblock2": "", "ageblock3": ...

Elevate your frontend development game with the powerful combination of Vue js 3

I've been attempting to add this dependency, but I keep receiving an error message stating that it doesn't exist and Vue 3 is unable to resolve the component. Click here to visit the npm page for vue-phone-number-input Any assistance you can pr ...

I am experiencing issues with editing the text field in React Tab as it keeps getting out of focus

https://i.sstatic.net/AUxlN.png Whenever I try to type, the text box loses focus and only allows me to type one letter at a time. Below is the code snippet that I am using: <TabPanel value={value} index={0}> {[...Array(commentCount)].map((item, in ...

Issue encountered while attempting to create entity in jhipster

After executing the creation of an entity in the command line, JHipster successfully generated Java and script files but encountered issues with updating the database. No new table was inserted despite starting MySQL and turning off the application befor ...

Switching things up with Angular-ui: New controller syntax for tab navigation

I'm currently working on integrating angular-ui bootstrap tabs into a basic application and running into issues with conflicting controller definitions or scope versions. var app = angular.module('plunker', ['ui.bootstrap']); // ...

Restangular: Avoiding empty parameter being passed

In my AngularJS application using RestAngular, I have the following controller method: $scope.findFriend = function (name, type, limit) { return FriendSearch.getList({ name: name, type: type, limit: limit ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

Creating a loading spinner in a Bootstrap 5 modal while making an XMLHttpRequest

While working on a xmlhttprequest in JavaScript, I incorporated a bootstrap spinner within a modal to indicate loading. The modal toggles correctly, but I am struggling to hide it once the loading is complete. I prefer using vanilla JavaScript for this ta ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

Am I causing my entire React component to re-render needlessly every time the state changes?

I've been attempting to develop an accordion component using React, but I seem to be encountering issues with the animation not functioning as expected. The approach I'm taking is quite standard - setting a max-height of 0 for each item body and ...

Send myArray via ajax to php

Hey there, I'm currently working on passing an array called myArray to PHP. <script type = "text/javascript" > $(document).ready(function () { var tagApi = $(".tm-input").tagsManager(); var myArray = []; jQuery(".t ...

The date of posting will always be '0000-00-00 00:00:00'

I'm experiencing an issue with my JavaScript code for writing reviews. Previously, it worked fine, but now the 'datePosted' column consistently outputs the default '0000-00-00 00:00:00'. writeReview(request, respond) { va ...

Firefox detects video interference from webcam

Take a look at this test code: <!doctype html> <html> <body> <video id="v1" autoplay="autoplay"></video> <script> navigator._getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserM ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

Ways to efficiently incorporate data into App.vue from the constructor

My app initialization uses main.js in the following way, import App from './App.vue'; const store = { items: [{ todo: 'Clean Apartment.', },{ todo: 'Mow the lawn!', },{ todo: 'Pick up ...