我正在创建一个示例应用程序,用户注销时间为15分钟。
2分钟之前,用户会弹出带有警告消息的倒计时弹出窗口。
有两个按钮。


注销=>用于注销。
StayLogin =>获得额外的15分钟进入应用程序的时间。


第一次,当用户达到13分钟时,弹出窗口。
因此,当单击继续按钮时,将增加注销时间。

问题:
计数器的问题。如果计数器到达0秒0分钟,它已重定向到登录页面。
在计数器之间,用户单击,又添加了15分钟,但计时器到达0秒,然后转到登录页面。

function countdown(minutes) {
  var seconds = 60;
  var mins = minutes

  function tick() {
    var counter = document.getElementById("timer");
    var current_minutes = mins - 1
    seconds--;
    counter.innerHTML =
      current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
    if (seconds === 0) {
      $state.go("root"); // problem
    }
    if (seconds > 0) {
      setTimeout(tick, 1000);
    } else {
      if (mins > 1) {
        alert('minutes');
        // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
        setTimeout(function() {
          countdown(mins - 1);
        }, 1000);
      }
    }
  }
  tick();
}
countdown(1); * *

// staylogin

$rootScope.proceed = function() {
  var lastDigestRun = Date.now();
  var s = lastDigestRun + 3 * 60 * 1000;
  var displaytime = now - lastDigestRun > 3 * 60 * 1000;
  if (now - lastDigestRun > 2 * 60 * 1000) {
    clearTimeout(tick);
    load();
  }
}


单击stayLogin按钮时如何停止计数器?

最佳答案

您需要使用类似

$timeout.cancel(timer)


取消计时器并重新创建一个计时器。

看看下面我将如何做。



var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $timeout, $interval) {
  $scope.name = 'MyConfusedUser';
  $scope.firstLoad = true;
  $scope.loggingOut = false;
  $scope.loggOutIn = 5;
  $scope.loggingOutIn = 10;
  $scope.maxLoginTime = 10;

  $scope.getTimer = function(seconds){
    return $timeout(function(){
      alert('you are logged out');
    }, seconds * 1000);
  }
  $scope.resetTime = function(){
    $timeout.cancel($scope.currentTimer);
    $scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
    $scope.loggingOutIn = $scope.maxLoginTime;
    $scope.loggingOut = false;
  }
  if($scope.firstLoad){
    $scope.firstLoad = false;
    $interval(function(){
      $scope.loggingOutIn--;
      if($scope.loggingOutIn < $scope.loggOutIn){
        $scope.loggingOut = true;
      }
    }, 1000, 0);

    $scope.timers = [];
    $scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <body ng-app="myApp" ng-controller="MainCtrl">
    <div ng-hide="loggingOut">
      <p>Hello {{name}}!</p>
    </div>
    <div ng-show="loggingOut">
      <p>{{name}}, you will be logged out very soon.</p>
    </div>
    <p>Logging out in {{loggingOutIn}} seconds</p>
    <p ng-show="loggingOut"><button ng-click="resetTime()">Reset Time</button></p>
  </body>

关于javascript - 如何通过单击按钮停止另一个函数调用中的setTimeout计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41188010/

10-09 18:21
查看更多