简体   繁体   English

如何取消javascript中间隔内的函数调用?

[英]How can I cancel a function call that's inside an interval in javascript?

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. 用户单击编辑图标时,将调用editRow()函数,这将打开一个模型窗口。 After this the code tries to save data every second by calling factory.submitItem. 此后,代码尝试通过调用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. 我如何做到这一点,以便如果factory.submit条目entityResource.update失败,则间隔将被取消,并且代码停止每秒进行一次保存。

     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;
            }
        },
myInterval = window.setInterval(function () {
    .....
}, 1 * 60 * 1000);

and when you want to cancel.... 以及何时要取消...

window.clearInterval(myInterval);

setInterval() returns an interval ID, which you can pass to clearInterval(): setInterval()返回一个间隔ID,您可以将其传递给clearInterval():

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

You can cancel it with: 您可以使用以下方法取消它:

clearInterval(yourInterval);

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM