Angular Timer
HTML
<body>
<div ng-app='TimerApp'>
<div ng-controller="TimerCtrl">
{{time}}
<button ng-click='startTimer()'>Start</button>
</div>
</div>
JavaScript
angular.module('TimerApp', [])
.controller('TimerCtrl', function($scope, $timeout) {
$scope.counter = 20;
var secs = $scope.counter % 60;
if (secs.toString().length == 1) {
secs = secs + '0';
}
$scope.time = Math.floor($scope.counter / 60) + ':' + secs //time representation..
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;
}
// var secs = 300;
$scope.counter--;
//decrement the clock representation...
var secs = $scope.counter % 60;
if (secs.toString().length == 1) {
secs = '0'+secs;
}
$scope.time = Math.floor($scope.counter / 60) + ':' + secs;
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!');
}
});
});