gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:20:13 25 4
gpt4 key购买 nike

我已经在 SO 上查看过,并在 Google 上搜索过,但我正在努力寻找解决方案。

我有以下函数,当我不使用 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 */]);`

关于javascript - 为什么 setTimeout 阻止递归 $http.get 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18895179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com