Is there a way to terminate a function call that is embedded within a JavaScript interval?

Reviewing the following code snippet (with some lines omitted for clarity), the editRow() function is triggered when a user clicks an edit icon, opening a modal window. Subsequently, the code attempts to save data every second by calling factory.submitItem. The process functions correctly except in cases where there is a failure in saving the data.

Is there a way to modify the code so that if factory.submit item entityResource.update encounters an error, the intervals are terminated and the continuous saving process is halted?

     var factory = {

        gridSetup: function ($scope) {
            $scope.editRow = function (row, entityType) {
                // modal functionality occurs here
                window.setTimeout(function () {
                    window.setInterval(function () {
                        factory.submitItem($scope, $scope.modal.data);
                    }, 1 * 60 * 1000);
                    factory.submitItem($scope, $scope.modal.data);
                }, 1 * 60 * 1000);
            }
        },

        submitItem: function ($scope, formData) {
            var idColumn = $scope.entityType.toLowerCase() + 'Id';
            var entityId = formData[idColumn];
            switch ($scope.modal.action) {
                case "edit":
                    var entityResource = $resource('/api/:et/:id', { et: $scope.entityType }, { update: { method: 'PUT' } });
                    entityResource.update({ id: entityId }, formData,
                        function (result) {
                            angular.copy(result, $scope.modal.data);
                        }, function (result) {
                            // how should this be handled?
                        })
                    break;
            }
        },

Answer №1

let interval = window.setInterval(function () {
    .....
}, 1 * 60 * 1000);

To stop the interval....

window.clearInterval(interval);

Answer №2

setInterval() provides an interval ID that can be used to stop the interval with clearInterval():

var myInterval = setInterval(function(), time);

To stop it, use:

clearInterval(myInterval);

Answer №3

There is a possible alternative approach to achieve the desired outcome. Consider implementing the following structure:

let allGood = true;

function executeAction(){
    if (allGood) {
        setTimeout(executeAction(), 5000);
    } else {
        allGood = false;
        return true;
    }
}

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

Code coverage analysis in a node.js TypeScript project consistently shows no coverage metrics

I'm currently working on a backend TypeScript project where I'm aiming to obtain coverage reports for unit test cases. However, Jest is returning empty coverage reports both in the terminal and in the HTML report, with no information provided. Ev ...

Is there a way to change the name of a file using the loopback storage service

I need help renaming the file that was uploaded to the server. I'm not sure how to change the file name and then send the new URL. I am working with [loopback-storage-service] Should I make modifications in the container model? Any assistance would ...

Reviewing packages often reveals a multitude of mistakes

I attempted to address some issues in my project by executing npm audit fix Unfortunately, this did not yield significant results. However, when I added the --force flag, the outcome was even worse than before: fix available via `npm audit fix` 10 vulner ...

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

What is the best way to organize a json based on numerical values?

Can anyone guide me through sorting a JSON data into an array based on numeric value, and then explain how to efficiently access that information? {"362439239671087109":{"coins":19},"178538363954003968":{"coins":18},"234255082345070592":{"coins":137}} Th ...

The scrollbar on the side of my page seems to be malfunctioning

I'm having an issue with the collapsible sidebar and tabs on my angularjs page. The scroll bar is not appearing when there is overflow in the sidebar. I've tried setting the scrollbar height to auto and overflow-y to scroll, but it's not wor ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

You cannot click on a React subcomponent

I am currently working on implementing a "Title" component within a header. The idea is that when you click on the title component, a header will appear with various buttons for formatting options such as bold and underline. This concept was inspired by a ...

Understanding the useQuasar() function in Pinia store file with VueJS

I've encountered an issue in my VueJS + Quasar project where I'm trying to utilize useQuasar() in my store file gallery.js, but it keeps returning undefined. A similar problem arose when I was attempting to access useRouter(), however, I managed ...

Transforming JSON dates to Javascript dates using AngularJS and ASP.NET

How can I convert a JSON date /Date(1454351400000)/ into a proper date format using AngularJS and ASP.NET? $http.get('/home/GetProducts') .success(function (result) { $scope.products = result; }) .error(function (data) { ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

How can we stop the Replace function from replacing spaces as well?

When I trigger a paste event in an input field, I have a method that replaces all special characters. However, it is also removing empty spaces between words. How can I prevent this from happening? checkSpecialCharacters(){ let value = this.form.get(&q ...

The need for incorporating a different directive controller within a subdirective

I have a formQuestionnaireItem Directive specified in the template for the formQuestionnaireItemsGroup Directive. In the formQuestionnaireItem directive, I need to include "^formQuestionnaireItemsGroup" The main form: <form name="formQuestionnaire" au ...

What causes the state hook in react to alter every single property within the object?

I have a list of team members and each member is associated with the same set of applications. I created 2 classes to link each member with their respective applications, resulting in a comprehensive list of all members and applications. This list was init ...

Main navigation category as parent and secondary category as a child menu in WordPress

Hello there, I am looking to create a navigation menu with parent categories displayed horizontally and child categories as corresponding submenus. For example, The parent categories would be Apple, Orange, and Mango Under Apple, we would have apple1, ...

npm ERR! Your operating system has denied the operation

When attempting to install create-react-app globally using 'npm install -g create-react-app', an error occurred due to insufficient write access to the /usr/local/lib/node_modules directory. The error message displayed was as follows ...

Generate Array of Consecutive Dates using JavaScript

My array contains the following values (for example): [ 1367848800000: true, 1367935200000: true, 1368021600000: true, 1368108000000: true, 1368194400000: true, 1368367200000: true, 1368540000000: true, 1 ...

What is the reason behind Azure Identity's choice of Browserflow over nodeflow for integration in my Next.js application?

Embarking on my inaugural project with Next.js, I find myself in unfamiliar territory. Rather than joining existing projects, I am constructing apps from scratch, encountering a challenge with Azure Identity along the way. Upon delving into the node module ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...