The AngularJS $rootscope $destroy event is not being triggered, resulting in timeouts not being cancelled

Below is the code snippet that I am currently working with:

function initialize() {
  var defer = $q.defer();
  var deferTimer = $q.defer();

  var cancelTimeout = $timeout(function() {
    if (defer !== null) {
      ctrlr.setProcessingParameters('XXX');
      defer = ctrlr.openProgressBar();
      deferTimer.resolve();
    }
  }, 1000);

  deferTimer.promise.then(function() {
    var cancelTimeout2 = $timeout(function() {
      if (defer !== null) {
        defer.resolve();
        ctrlr.setProcessingParameters('Please Wait...');
        defer = ctrlr.openProgressBar();
      }
    }, 4000);
  });

  //Process Backend service n resolbve defer....

}

// Cancel the $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("Cancelling timeout..");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeout);
    cancelTimeout = null;
  }
});

// Cancel the second $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("Cancelling timeout2..")
  if (cancelTimeout2) {
    $timeout.cancel(cancelTimeout2);
    cancelTimeout2 = null;
  }
});

I'm facing an issue where the loggers are not printing and the debugger doesn't seem to enter the $destroy function. Any insights on what might be causing this would be greatly appreciated.

Answer №1

Once you close or navigate away from the page, $rootScope is destroyed and everything it contains will be lost without any need for clean up.

To properly manage resources, you should use $destroy on the $scope instead.

$scope.$on('$destroy', function() {
  logger.log("Cleaning up timer tasks");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeoutProcess);
    cancelTimeout = null;
  }
});

In the controller, $scope.$on('$destroy') will be triggered when the controller gets destroyed, associated only with the current $scope.

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

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

React application encountering issues with the use of Redux actions within a custom module

I have been facing a problem with my util module. It seems that when I try to use a Redux action, it does not function as expected. import {openloading} from '../actions/loading' export default function (e) { openloading(e.font); } Interest ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Issue with div element not stretching to 100% width

I am currently working on a fluid layout design where the template includes a header, menu, and body section. <div class="w100 h100"> <div id="headerBox" style="height: 10%;" class="w100"> <div style="width: 80%;" class="lfloat ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Webpack dynamically imports files from a folder

In order to streamline my development process, I have a specific structure for organizing React components. Each main component has its own components folder right alongside it. Currently, I find myself manually importing each component from the components ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Twice within a controller, alert is displayed in AngulasJS, OnsenUI, and Phonegap

I'm currently developing a mobile application using AngularJS, OnsenUI, and PhoneGap to package it for Android devices. However, I've encountered a strange issue where an alert box pops up twice when the application is run as a new process. I&ap ...

Creating a form within a material dialog using AngularJS

Can you provide guidance on effectively using a form within a $mdDialog popup with submit functionality? I've been trying to implement this feature but have encountered difficulties. ...

JavaScript's wildcard character, *, in a regular expression will always match something

I am currently attempting to verify whether a given string contains only uppercase letters, numbers, and underscores by utilizing the pattern matching approach with /[A-Z0-9_]*/. Despite this, executing the following code results in a return of true: /[A ...

Is there a way to make my red div switch its background color from red to green when I press the swap button?

How can I make the red div change its background color to toggle between red and green when I click on the swap button in the following code? $(document).ready(onReady); var numberOfClicks = 0; function onReady() { console.log('inside on ready ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Creating objects based on user input in AngularJS is a common task for developers. This tutorial will

When populating a form with radio buttons based on a JSON object, the user can select options and upon clicking submit, all radio button data is saved into an object. <form name="regForm"> <ul> <li ng-repeat="q in ...

Why does the HTML and CSS slider fail to load upon page refresh, yet works perfectly when the next or previous button is clicked?

There seems to be an issue with the slider images not loading on page refresh. Oddly enough, they appear only after clicking the next button. However, upon refreshing the page again, the images disappear. <div class="slide-banner"> < ...

Building Unique Staircases with Three.js Geometry

I have been working on creating a custom three.js geometry for round staircases, but I seem to have made some errors with the vertices and indexes of the steps. Below is an example staircase that utilizes my custom geometry: https://i.sstatic.net/uQXvP.j ...

Add the useState hook from React to an array

Hey there, I need some help with my code. I am trying to add an element to my array, but it's not working as expected. Can you take a look at what I have written below? const [datesState, setDisabledData] = useState([ format(new Date(2021, 4, 1) ...

Is it possible to remove an element from a data structure in a web application using an HTTP command?

Apologies for the confusing title, I struggled to find a better way to describe it. Imagine sending a GET request to an API and receiving this data: { {id: 1, name: "John Doe", tags: ["Apple", "Orange", "Pear"]}, {id: 2, name: "Jane Doe", tags: [ ...

Using jQuery to encapsulate HTML within a div tag

I am looking to insert some HTML markup into my webpage using jQuery. I want to wrap the highlighted yellow code below with <div class="section">...</div>. Here is an example of what I need: <div class="section"> <div>...< ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...