How can I cancel or reset a timeInterval in AngularJS?

In my project demo, I have implemented a feature that fetches data from the server at regular intervals using $interval. Now, I am looking for a way to stop or cancel this process. Can you guide me on how to achieve this? And if I need to restart the process, what is the best approach?

Additionally, I have another query: while fetching data from the server periodically, do I need to use $scope.apply or $scope.watch? Your insights on this will be highly appreciated.

Check out my plunker below:

  app.controller('departureContrl',function($scope,test, $interval){
   setData();

   $interval(setData, 1000*30);

   function setData(){
      $scope.loading=true;
    test.stationDashBoard(function(data){
        console.log(data);
        $scope.data=data.data;
        $scope.loading=false;
        //alert(data);
    },function(error){
        alert('error')
    }) ;

   }
});

http://plnkr.co/edit/ly43m5?p=preview

Answer №1

To efficiently manage intervals in AngularJS, you can save the promise returned by the interval function and later use $interval.cancel() to stop it when needed. By creating separate functions like start() and stop(), you can control the initiation and termination of intervals based on specific events. Below is a simple example illustrating how to start and stop an interval using event triggers (e.g., ng-click) in both the view and controller.

angular.module('app', [])

  .controller('ItemController', function($scope, $interval) {
  
    // store the interval promise in this variable
    var promise;
  
    // simulated items array
    $scope.items = [];
    
    // function to start the interval
    $scope.start = function() {
      // stop any existing interval before starting a new one
      $scope.stop(); 
      
      // save the interval promise
      promise = $interval(setRandomizedCollection, 1000);
    };
  
    // function to stop the interval
    $scope.stop = function() {
      $interval.cancel(promise);
    };
  
    // start the interval by default
    $scope.start();
 
    // stop the interval when the scope is destroyed
    $scope.$on('$destroy', function() {
      $scope.stop();
    });
            
    function setRandomizedCollection() {
      // generate random items from 1 to 11
      var randomItems = parseInt(Math.random() * 10 + 1); 
        
      // clear the items array
      $scope.items.length = 0; 
      
      // add random numbers to the items array
      while(randomItems--) {
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); 
      }
    }
  
  });
<div ng-app="app" ng-controller="ItemController">
  
  <!-- Button to start the interval -->
  <button type="button" ng-click="start()">Start Interval</button>
  
  <!-- Button to stop the interval -->
  <button type="button" ng-click="stop()">Stop Interval</button>
  
  <!-- Display random items -->
  <ul>
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>
  </ul>
  <!-- end of display -->
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Answer №2

let timer = setInterval(function() {
  console.log('greet');
}, 1000);

clearInterval(timer);

Answer №3

let countdown = $interval(function(){
    if($location.path() === '/start'){
        $rootScope.$emit('newData',"example");
        $interval.cancel(countdown);
    }
},1500);

Answer №4

If you're looking to set up an interval storage promise in a variable, follow these steps:

const intervalPromise = $interval(function() { ... }, 1000);

To stop or clear the interval, all you need to do is this:

$interval.cancel(intervalPromise);

Answer №5

    $scope.controlSideBarDelayed = function(){
        var timer = $interval(function(){
            $scope.toggleSidebar();
        },1000,1)
        .then(function(){
            $interval.cancel(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

The Pino error log appears to be clear of any errors, despite the error object carrying important

After making an AXIOS request, I have implemented a small error handling function that is called as shown below: try { ... } catch (error) { handleAxiosError(error); } The actual error handling function looks like this: function handleAxiosError(er ...

Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this: <script>window.alert("hello");</script> When I test the site with "Gatsby ser ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

What is the best way to pass a variable between clusters in a Node.js application?

I have implemented clusters in my express application, where the master node has a caching system with a variable that needs to be shared across worker nodes. I am looking for a way to achieve this without using a physical datastore. Can the following ap ...

Issue encountered when attempting to transfer data to MongoDB using custom API

Currently, I have been working on a flutter application that is designed to send data to my custom API built in node js. This API then forwards the data to a MongoDB cluster. While testing the API, everything was functioning correctly and the data was succ ...

Why are NodeJS and Jade/Pug variables not being recognized in the Jade script?

After successfully passing a variable to Jade like #{myvar}, I encountered an issue when trying to access it in a script block. Despite using typeof(myvar) and confirming that it was initially undefined, my attempts to display its value within the script b ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

Exploring the use of leaflets within LitElement

I have been working on a project involving LitElement components and I am looking to incorporate Leaflet into it. However, I am encountering difficulties with displaying the map properly. After installing Leaflet through npm in my project, I created a clas ...

Tips for developing a versatile code for passport.authenticate

I have a scenario where multiple controllers contain various methods that require user authentication to access database data. I am currently attempting to streamline the authentication process to avoid repetition in my code. Within the controller: const ...

Iterate over the array elements in React by using Hooks on click

I am facing an issue with loading objects separately from a JSON file when a button is clicked. The problem occurs when the index goes out of bounds, resulting in a TypeError "Cannot read property 'content' of undefined" message. I have tried u ...

VueJS Unit Testing: Exploring the Content of Attributes- What to Test?

I'm currently facing some challenges with my initial VueJS unit tests using Jest. Although I grasp the concept and have already executed my first set of successful tests, I find myself pondering over the question of "What aspects should I test?" For ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...

Is there a way to integrate datatablejs with AngularJS or are there other options similar to datatablejs that can be

I'm facing a challenge with my application, as I have a large amount of data to generate reports and create data entry forms for users. In the past, I relied on JSON calls from the backend along with datatable.js to manage fixed headers and columns. ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...

Is there a way to link a knockout observable to the jquery barrating plugin?

I have integrated the jquery bar-rating plugin with a knockout viewModel. Currently, all ratings need to be manually selected, but I am looking to convert the variable (let's call it rating) into an observable so that the bar automatically updates whe ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Struggling to display a PHP success message using AJAX

So I have this code where I am trying to create a form in PHP and send a message. The message is being submitted successfully, but I am facing an issue when it comes to displaying a success message. The page submits the data but does not show any output. H ...

Generating views for individual models in a backbone collection

Currently, I am developing a small backbone.js application that simulates a library where CRUD operations can be performed. The core components of this application are the book model and the library collection (which stores books). var Book = Backbone.Mod ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...