Gaurav Kumar
Gaurav Kumar

Reputation: 241

how to pause and resume the timer when using $timeout in angularjs

i used this code for pause timer:

when using $timeout in angularjs how to implement pause and resume functionality

$scope.pause = function(){
             window.clearTimeout(t);

        }

timedcounter = function () {
       time = time + 1;
       localStorage.autotimertime = time;
       t = $timeout(timedcounter, 1000);
       display(time);
}

Upvotes: 1

Views: 1991

Answers (2)

Weedoze
Weedoze

Reputation: 13943

In this snippet, I am showing the time and a button is used to stop/restart the timeout.

You should add your logic inside the onTimeout function

var app = angular.module('myapp', []);
app.controller('myCtrl', function($scope, $timeout) {
  $scope.time = 0;
  $scope.stopped = false;

  $scope.onTimeout = function() {
    $scope.time = $scope.time + 1;
    //Your logic here
    //localStorage.autotimertime = time;
    //display(time);
    mytimeout = $timeout($scope.onTimeout, 1000);

  }

  var mytimeout = $timeout($scope.onTimeout, 1000);

  $scope.stopTimeout = function() {
    $scope.stopped = true;
    $timeout.cancel(mytimeout);
  }

  $scope.restatTimeout = function() {
    $scope.stopped = false;
    mytimeout = $timeout($scope.onTimeout, 1000);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myCtrl">
  <p ng-bind="time"></p>
  <button ng-click="stopTimeout()" ng-show="!stopped">STOP ME !</button>
  <button ng-click="restatTimeout()" ng-show="stopped">RESUME ME!</button>
</div>

Upvotes: 1

Murali
Murali

Reputation: 324

To cancel a timeout request, call $timeout.cancel(promise).

Upvotes: 0

Related Questions