0

I have the following code here (with some lines removed to make it more clear). When a user clicks an edit icon the editRow() function is called and this opens a model window. After this the code tries to save data every second by calling factory.submitItem. Everything works okay except if there's a problem saving the data.

How can I make this so that if factory.submit item entityResource.update fails then the intervals are cancelled and the code stops doing a save every second.

     var factory = {

        gridSetup: function ($scope) {
            $scope.editRow = function (row, entityType) {
                // modal stuff happens 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) {
                            // what to put here ?
                        })
                    break;
            }
        },
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 2
    This might help you: http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – Igl3 Oct 24 '13 at 08:05

3 Answers3

2
myInterval = window.setInterval(function () {
    .....
}, 1 * 60 * 1000);

and when you want to cancel....

window.clearInterval(myInterval);
Cameron Askew
  • 1,403
  • 1
  • 12
  • 20
1

setInterval() returns an interval ID, which you can pass to clearInterval():

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

You can cancel it with:

clearInterval(yourInterval);
Igl3
  • 4,900
  • 5
  • 35
  • 69
0

You could do something diferent to do that. The scheme could be like this:

var everythingIsOk = true;

function doSomething(){
    if (everythingIsOk) {
        setTimeout(doSomething(),5000);
    } else {
       everythingIsOk = false;
       return true;
    }
}
fray88
  • 820
  • 1
  • 7
  • 23
  • Thank you for taking the time to answer but we are looking for a solution that uses are existing code. What we just need is some way to stop the iterations if there is failure with the auto update. – Samantha J T Star Oct 24 '13 at 08:31