AngularJS 取消超时

AngularJS cancelling a timeout

我有一个使用 AngularJS 和 Onsen/Monaca UI 开发的跨平台应用程序。

我有一个功能可以监视按钮点击的变化,如果检测到某个按钮的点击次数达到一定数量,用户就会被带到确认屏幕。

但是,如果用户用 select 按钮的时间太长,则应将它们重定向到另一个屏幕(尚未定义)。

我正在尝试用它来实现 $timeout 功能,但是一旦用户 select 按下按钮的次数正确,我似乎无法取消 $timeout。如果用户 select 在允许的时间内点击按钮,它们将被带到确认页面,但 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);
    },
}

尝试使用这个

$timeout.cancel(timer);

但是你需要在 if

之前定义定时器

您正在$scope.$watch中创建timer,如果timer创建多次且只保留一个变量,您只能通过[=16=取消最新的一个].所以解决方案应该是将 $timeout 部分移出 $scope.$watch 或将计时器保留在数组中并循环数组以停止它们。

如果您仍然坚持在$scope.$watch中使用,请在创建新的之前取消之前的。

if (timer) {
    $timeout.cancel(timer);
}
timer = $timeout(function () {
    alert("You are taking too long to respond");
}, 10000);

参考下面的代码片段。

  • 在 angular 结束呈现页面后创建 timer
  • test 更改后,将创建 timer

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>