I have AngularJS code for a timer where, on starting the counter, the timer starts its countdown backward from 300 to 0. It is working fine. But now I want to replace 300 with MM:SEC format(clock) i.e.,5:00 and go on and end at 0:00 which I am unable to do. My code
angular.module('TimerApp', [])
.controller('TimerCtrl', function($scope, $timeout) {
$scope.counter = 300;
var mytimeout = null; // the current timeoutID
// actual timer method, counts down every second, stops on zero
$scope.onTimeout = function() {
if ($scope.counter === 0) {
$scope.$broadcast('timer-stopped', 0);
$timeout.cancel(mytimeout);
return;
}
$scope.counter--;
mytimeout = $timeout($scope.onTimeout, 1000);
};
$scope.startTimer = function() {
mytimeout = $timeout($scope.onTimeout, 1000);
};
// stops and resets the current timer
$scope.stopTimer = function() {
$scope.$broadcast('timer-stopped', $scope.counter);
$scope.counter = 30;
$timeout.cancel(mytimeout);
};
// triggered, when the timer stops, you can do something here, maybe show a visual indicator or vibrate the device
$scope.$on('timer-stopped', function(event, remaining) {
if (remaining === 0) {
console.log('your time ran out!');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app='TimerApp'>
<div ng-controller="TimerCtrl">
{{counter}}
<button ng-click='startTimer()'>Start</button>
</div>
</div>
Working JSFiddle for above: http://jsfiddle.net/fq4vg/1796/