我正在尝试使用 Angular $timeout 运行循环。 事情是这样的: 当我尝试使用这个 $timeout 用法时。我每秒收到近 15 个请求,而不是计划的每 2 秒 1 个:
$timeout($scope.checkChallengeAnswerd(challengeTarget), 2000);
但是如果我这样做的话一切都很好:
$timeout(function() { $scope.checkChallengeAnswerd(challengeTarget); }, 2000);
谁能解释一下为什么会发生这种情况吗?
这是完整的功能代码块:
$scope.checkChallengeAnswerd = function (challengeTarget) {
$http({
method: 'post',
url: CHESS_URL + "/challenge/check_answerd/",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { "target":challengeTarget }
}).success(function (data, status, headers, config) {
$scope.answerd = data.answerd;
if ($scope.answerd == "wait") {
//alert("wait");
$timeout(function() { $scope.checkChallengeAnswerd(challengeTarget); }, 2000);
}else{
$("div.b111").hide();
alert($scope.answerd);
};
});
};
最佳答案
$timeout
服务将第一个参数作为函数,第二个参数是等待执行该函数的毫秒数。
当您使用$timeout($scope.checkChallengeAnsward(challengeTarget), 2000)
时,
您没有将函数传递到 $timeout 服务,而是传递函数的返回值。
当您将函数传递给 $timeout
服务时,使用 $timeout(function() { $scope.checkChallengeAnswerd(challengeTarget); }, 2000)
可以正常工作。
其他选项是将 $scope.checkChallengeAnsward(challengeTarget) 函数表达式修改为:
$scope.checkChallengeAnswerd = function (challengeTarget) {
return function () {
$http({
method: 'post',
url: CHESS_URL + "/challenge/check_answerd/",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { "target": challengeTarget }
}).success(function (data, status, headers, config) {
$scope.answerd = data.answerd;
if ($scope.answerd == "wait") {
//alert("wait");
$timeout(function () { $scope.checkChallengeAnswerd(challengeTarget); }, 2000);
} else {
$("div.b111").hide();
alert($scope.answerd);
};
});
};
};
关于javascript - AngularJS $timeout 的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451987/