Javascript 清除间隔不工作
这是我的控制器:Javascript 清除间隔不工作,javascript,angularjs,Javascript,Angularjs,这是我的控制器: .controller('mainController', function($http, $scope, $timeout, $sce, updateService) { updateData = function() { updateService.getDataA($http, $scope); updateService.getDataB($http, $scope, $sce); } v
.controller('mainController', function($http, $scope, $timeout, $sce, updateService) {
updateData = function() {
updateService.getDataA($http, $scope);
updateService.getDataB($http, $scope, $sce);
}
var updateIntervalId = setInterval(updateData, 1000);
})
现在,当用户刷新页面时,仍然会发出旧的请求,我试图通过将其置于interval调用下来取消请求:
window.onbeforeunload = function() {
console.log('interval killed');
clearInterval(updateIntervalId);
}
控制台正在记录“interval killed”(间隔终止),因此正在执行,但仍在发出请求,为什么?让我们以角度方式执行 在控制器中注入
$interval
服务
并将代码更新为以下内容
var intervalPromise = $interval(updateData, 1000);
$scope.$on('$destroy', function() { // Gets triggered when the scope is destroyed.
$interval.cancel(intervalPromise );
});
并删除
window.onbeforeunload
事件处理程序。当涉及angularJS时,我总是建议使用它来处理间隔,因为它与angularJS隐藏机制一起工作得更好
然后,如果事件
window.onbeforeunload
位于控制器外部,您将永远无法访问updateIntervalId
,因为它位于另一个作用域内,因此,您应该使其成为全局变量。使用var updateIntervalId
将变量updateIntervalId
绑定到回调函数函数的作用域($http、$scope、$timeout、$sce、updateService){
因此它无法从您的onbeforeunload
回调访问。最好不要使用窗口。无论如何,onbeforeunload
都是因为onbeforeunload
可以被任何其他代码更改,因此它不可靠。最好使用窗口。addEventListener(“beforeunload”,…)
并将其放在var updateIntervalId=setInterval(updateData,1000);
您完全正确,我只是指出问题可能是不同的范围!