Prevent callback function execution in JavaScript

Users have the ability to select a month by clicking +1 month or -1 month.

Each click triggers a loop based on the number of days in the chosen month.
Within the loop, a function is called to fetch data through an $http request.

The issue at hand is as follows: (for example)
-When the page loads: var data = [];

-Time 1: User clicks on January:
31 $http requests are made, resulting in 15 callbacks.
data.length = 15;

Time 2: User clicks on February.
The variable is reset with var data = []
15 callbacks from the previous month carry over, in addition to 30 callbacks from February.

I am looking for a solution to halt callbacks when the user switches to another month...

For a clearer demonstration, check out this basic Fiddle:
http://jsfiddle.net/36qp9ekL/318/

Answer №1

My apologies for the confusion earlier with the incorrect code...

It seems that your requests are not being processed as quickly as expected. Due to the asynchronous nature of Angular, when you rapidly click the next() and previous() functions, they end up overlapping. This causes the "rest" from previous days to be returned before moving on to the next days of the month. To address this issue, consider implementing promises or restructuring your program logic.

Additionally, make sure to include $q for injection.

Here is an example using promises:

$scope.next = function(){
    date.setDate(date.getDate() + 1);
    $scope.data = [];
    // disable previous and next button
    $scope.loadData().then(function(allDayRequestResults) {
        $scope.data = allDayRequestResults;
        // enable previous and next button
    }).catch(function(error) {
        // handle http request error here
    });
};

$scope.loadData = function(){
    var promises = [];
    for(var i = 1; i <= daysInMonth(); i++){
        promises.push(getData(i));
    }
    return $q.all(promises);
};

function getData(i){
    var deferred = $q.defer();

    $http(<yourHttpOptions>)
        .success(function(result) {
            deferred.resolve(result);
        })
        .error(function (data, status, headers, config) {
            console.log('$http-error:' + data + status + headers + config);
            deferred.reject('Error occured while retrieving day '+ i);
        });

    return deferred.promise;
}

This solution has not been thoroughly tested yet...

Answer №2

While I agree that requesting 1 callback with a response time of 30 days may be a better solution, I believe that this approach could also be useful for other applications.

Although untested, this code provides a potential way forward. I have opted for global variables as a solution because promises may not work across all browsers.

<button ng-click="load()"> Load data 1,000 times </button>

<script>

var callback = true;
var count = 0;

function ajaxRequest(i){

   // AJAX REQUEST
   .success(function(){

       count++;
       if(count == 1000){
         callback = true;
         count = 0;
       }
    });


}

$scope.load = function(){

   if(callback){
     callback = false;

     for(var i = 0; i < 1001; i++){
        ajaxRequest(i);
     }

   }

}
</script>

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

loop through nested arrays

My goal is to use ng repeat in Angular to iterate through a child array of a multidimensional array. The json object I am working with is as follows: $scope.items = [{ "id":1, "BasisA":"1", "Basis":true, "personSex": ...

Disable the swipe feature on a Bootstrap carousel to prevent users from navigating through slides on mobile devices. The attribute data-touch="

I've been attempting to deactivate the swipe function on my Bootstrap 4 carousel in my project, but it's proven to be quite challenging. Despite it being a basic carousel, I'm finding it difficult to turn off this feature. What am I missing ...

Load pictures featuring a designated title

I have a collection of images stored in different categories: image-1-1.jpg image-2-2.jpg image-2-3.jpg image-2-4.jpg image-2-5.jpg image-3-1.jpg image-3-2.jpg image-3-3.jpg ... In addition, I also have links that correspond to each category: link 1 link ...

Summing Values with Linq.js Filter

Can you apply a filter in Linq.JS using SUM? This is my attempt: var query = Enumerable .From(self.data()) .Where("$$.Sum($.percent) > 100") .ToArray(); Issue encountered: linq.js: Uncaught TypeError: $$.Sum is ...

Tips for presenting JSON date in JavaScript using Google Chart

I am in urgent need of assistance with this issue. I am trying to display the date from PHP JSON data retrieved from my database in a Google Chart using JavaScript. Below is the PHP code snippet: $data_points = array(); while($row = mysqli_fetch_array($r ...

Utilizing the ng-controller directive from AngularJS within the class attribute

Hey everyone, I'm new to AngularJS and I'm trying to get this code to work. This code is actually from an AngularJS tutorial, but I made a small modification by changing all the directives to classes instead of attributes. The problem I'm ...

Bot is being inundated with messages containing no content

My discord.js version is 14.0.3. I'm facing an issue where the message content is not being retrieved correctly. To solve this, I set up a client.on('messageCreate') event handler: client.on('messageCreate', async (message) => ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Having trouble integrating the css and js animation files into my Django project

settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '@6qt%i+0&_=z0#zl^+!u3bw6c7dmg4e3khboj%7s7439z9#ky(' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin& ...

What is the process for retrieving the value of the 2nd td by clicking on the checkbox in the 1st td with JavaScript

When I click on "in", I am looking to retrieve the value of "out". This can be easily understood by referring to the image below: The timesheet displayed is generated using an array. All the data is stored in the array and needs to be presented in a table ...

I am eager to showcase a Pokémon image sourced from the API, but I am faced with the challenge of only having the image URL and not knowing how to display it effectively

As a beginner in programming, I am seeking some assistance. I have been able to retrieve a random Pokémon from an API and gather its data, including the ID, name, and picture. My main focus now is to display the image of the Pokémon in the custom modal I ...

Solving complex promises in both serial and parallel fashion

My current function performs four tasks that must be executed in a specific sequence: - promise1 - promiseAfter1 // In parallel - promise2 - promiseAfter2 To ensure the promises are handled sequentially, I have structured two separate functions as follows ...

Difficulty encountered in displaying HTML within a React component

Struggling to display HTML in my React code, whenever I click 'signup' after starting the page, it shows the 'login' view instead. Could there be an issue with how I'm linking everything together? App.js class App extends Compon ...

VueJS advisory: Refrain from directly altering a prop

When attempting to modify a prop value using the @click directive, I encountered a warning message: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed pr ...

Tips for adjusting an svg component to suit various screen sizes

I inserted the following SVG component into my HTML file. It fits perfectly on my tablet, but it's too large for my smartphone. How can we automatically adjust the size of the SVG to fit different screens? <svg viewBox="310 -25 380 450" w ...

The columnFilter plugin in Datatables is failing to initialize

I have a pre-existing table that needs to be customized and initialized properly. <table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table"> <thead> <tr> <th style="width: 10px;" ...

The data is not being filtered properly in Ionic Angularjs

Below is the code for my controller: $scope.professionList = []; $scope.searchText = ''; $scope.$on('$ionicView.enter', function() { PeopleSearchService.setSearchParams(undefined); }) $scope.$on('$ionicView.loaded', funct ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

Within AngularJS directives, one may find themselves utilizing services like $log or other similar

Here is the directive I have created to initialize the timeago plugin: Directives.directive('timeago', function() { return function(scope, element, attrs) { $(element).attr('title', scope.post.utc_posted); $(element).t ...

Cypress and Cucumber collaborate to reinitialize the requests within Next Js

In my upcoming project with Next.js, I am utilizing Cypress for testing a specific page. The objective is to validate two scenarios: 1. Successful outcome and 2. Error handling when a user encounters an issue. Before(() => { return void cy.server() ...