为什么 setTimeout 会阻止递归 $http.get 调用

Why is setTimeout preventing recursive $http.get call

本文关键字:http get 调用 递归 setTimeout 为什么      更新时间:2023-09-26

我已经在SO上查看了它,并在谷歌上搜索了它,但我正在努力找到任何解决方案。

我有以下函数,当我不使用 setTimeout() 函数而只是调用我的轮询函数时,它会按预期工作。但是当我尝试将我的轮询函数包装在setTimeout()中时,它工作一次,然后除非刷新页面,否则不会再次调用,我已经在 GET 请求中包含时间戳以防止使用缓存响应,所以我认为这不是问题所在。我也检查过,这种行为发生在IE9,Firefox和Chrome中。

$scope.progressPolling = function () {
    var time = new Date().toString();
    console.log("time :" + time);
    $http.get('pollprogress?time=' + time + '&id=' + $scope.jobID)
        .success(function (data, status, headers, config) {
            var percent = data.percentage;
            if (parseInt($scope.progress) < 100) {
                if (percent <= 100) {
                    $scope.progress = percent;
                }
                setTimeout(function() {
                    if (parseInt($scope.progress) < 100) {
                        temp = parseInt($scope.progress) + 1;
                        $scope.progressPolling();
                    };
                }, 5000);
            }
        })
        .error(function (data, status, headers, config) {
            console.log("Error updating Progress: " + data);
        });
}

尝试将其更改为$timeout

$scope.progressPolling = function () {
var time = new Date().toString();
console.log("time :" + time);
var stop;
$http.get('pollprogress?time=' + time + '&id=' + $scope.jobID)
    .success(function (data, status, headers, config) {
        var percent = data.percentage;
        if (parseInt($scope.progress) < 100) {
            if (percent <= 100) {
                $scope.progress = percent;
            }
           stop = $timeout(function() {
                if (parseInt($scope.progress) < 100) {
                    temp = parseInt($scope.progress) + 1;
                    $scope.progressPolling();
                }
                   else{
                     $timeout.cancel(stop);
                   }
            }, 5000);
        }
    })
    .error(function (data, status, headers, config) {
        console.log("Error updating Progress: " + data);
    });
}

作为旁注,创建工厂:

 myModule.factory('delay', ['$q', '$timeout', function ($q, $timeout) {
 return {
    start: function () {
        var deferred = $q.defer();
        $timeout(deferred.resolve, 5000);
        return deferred.promise;
      }
   };
 }]);

之后你可以像这样调用它:

$q.all([delay.start(), /*your method */]);`

setTimeout似乎不起作用的原因是回调函数在摘要周期之外执行,因此绑定不会更新。$timeout服务使用 $scope.$apply(...) 包装调用,以便更新 UI。 您可以在setTimeout回调中自己完成。