Javascript 为什么setTimeout会阻止递归$http.get调用
我在这两个网站上都查过了,并用谷歌搜索过,但我正在努力寻找解决办法 我有下面的函数,当我不使用Javascript 为什么setTimeout会阻止递归$http.get调用,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我在这两个网站上都查过了,并用谷歌搜索过,但我正在努力寻找解决办法 我有下面的函数,当我不使用setTimeout()函数,只调用我的轮询函数时,它会按预期工作。但是,当我尝试将轮询函数封装在setTimeout()中时,它只工作一次,然后不会再次被调用,除非页面被刷新,我已经在get请求中包含了一个时间戳,以防止使用缓存响应,所以我认为这不是问题所在。我也检查过,这种行为发生在IE9、Firefox和Chrome中 $scope.progressPolling = function () {
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);
});
}
$scope.progressPolling=函数(){
var time=新日期().toString();
console.log(“时间:+时间);
$http.get('pollprogress?time='+time+'&id='+$scope.jobID)
.success(函数(数据、状态、标题、配置){
var百分比=数据百分比;
if(parseInt($scope.progress)<100){
如果(百分比尝试将其更改为$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);
});
}
之后,您可以这样称呼它:
$q.all([delay.start(), /*your method */]);`
setTimeout
似乎不起作用的原因是回调函数在摘要周期之外执行,因此绑定不会更新。$timeout
服务将调用包装为$scope.$apply(…)
因此UI会更新。您可以在setTimeout
回调中自己执行此操作。尝试使用$timeout()
而不是setTimeout()
@CodeHater解决了这个问题谢谢,你知道是什么原因导致这个问题,或者$timeout有什么不同,它没有发生。解决了我的问题,你能解释一下是什么原因导致了这个问题,以及$timeout解决这个问题的方法吗?好吧,setTimeout
是jQuery,你需要$apply()
使用角度绑定。然而,$timeout
是角度方法,我的观点是,为了防止上述问题,仅使用角度:)
$q.all([delay.start(), /*your method */]);`