javascript - AngularJS 取消超时

标签 javascript angularjs timeout monaca

我有一个使用 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/

相关文章:

javascript - 粘性导航栏但有边距

node.js - Socket.io 仅向发出请求的客户端发送数据

python - pycurl/curl 不遵循 CURLOPT_TIMEOUT 选项

javascript - 从 WordPress 中的自定义插件加载脚本

javascript - Coffeescript 忽略函数的多个返回值中的一些

javascript - 从对象值检索图像 url - Angular JS

javascript - AngularJS Controller 如何访问非 AngularJS iframe 中的函数?

javascript - Angular 中指令和 Controller 之间的双向通信

java - 使用 EJB 计时器的 WebSphere 中的 Bean 事务超时

javascript - div从右滑动到全宽