我有一个使用 AngularJS 和 Onsen/Monaca UI 开发的跨平台应用程序。
我有一个功能可以监视按钮点击的变化,如果在按钮上检测到一定数量的点击,用户就会进入确认屏幕。
但是,如果用户选择按钮的时间过长,则应将他们重定向到另一个屏幕(尚未定义)。
我正在尝试用这个实现 $timeout 函数,但一旦用户选择了正确次数的按钮,我似乎无法取消 $timeout 。如果用户在允许的时间内选择按钮,则会进入确认页面,但 10 秒后仍会显示 $timeout 消息。
下面是我的实现。可以假设一切正常 - 除了 stop() 函数中的 $timeout.cancel() 。
// Initialise
var timer;
// Watch for changes on button clicks
$scope.$watch('currentAction', function(newValue, oldValue) {
if (counter == 6) {
// User clicked buttons - cancel the timer
stop();
// Segue to next page
Segue.goTo("confirmation.html");
}
else {
// Start the timer
timer = $timeout(function () {
alert("You are taking too long to respond");
}, 10000);
}
});
// Cancel the $timeout
function stop() {
$timeout.cancel(timer);
}
Segue.goTo() 只是将用户转到传入的页面(不相关,但为了清晰起见而包含在内)
var myFunctions = {
goTo: function (url) {
var nextPage = url;
var element = document.querySelector("ons-navigator");
var scope = angular.element(element).scope();
scope.myNavigator.pushPage(nextPage);
},
}
最佳答案
您正在$scope.$watch
中创建计时器
,如果计时器
被创建了多次并且只保留一个变量,您只能通过$timeout(timer)
取消最新的一次。因此,解决方案应该将 $timeout
部分移出 $scope.$watch
或将计时器保留在数组中并循环数组以停止它们。
如果您仍然坚持在$scope.$watch
中使用,则需要先取消前一个,然后再创建新的。
if (timer) {
$timeout.cancel(timer);
}
timer = $timeout(function () {
alert("You are taking too long to respond");
}, 10000);
引用下面的代码片段。
- 一旦 Angular 端渲染页面,就会创建
计时器
。 测试
更改后,将创建计时器
。
angular.module("app", [])
.controller("myCtrl", function($scope, $timeout) {
var timer;
$scope.$watch('test', function(newValue, oldValue) {
console.log('$timeout created. value:' + newValue);
timer = $timeout(function() {
console.log('$timeout fired. value:' + newValue);
}, 5000);
})
$scope.clickEvt = function() {
console.log('$timeout canceld. currentValue:' + $scope.test);
$timeout.cancel(timer);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<input type="text" ng-model="test">
<button ng-click="clickEvt()">Stop<button>
</div>
关于javascript - AngularJS 取消超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844422/