Javascript Timer
Simple implementation of a Timer for Javascript
HTML
<!-- stitch this with the module declare in Javascript -->
<body ng-app="myApp">
<div ng-controller="TimerCtrl">
<table class="timeTable">
<tr>
<td>
Status: {{msg}}<br>
Function 'update' has been executed': {{count}} 'times'
</td>
</tr>
<tr>
<td>
<button ng-click="startTimer()">Start Timer</button>
<button ng-click="stopTimer()">Stop and Reset Timer</button>
</td>
</tr>
</table>
</div>
</body>
CSS
.timeTable td{
text-align: center;
}
.timeTable td, .timeTable tr, .timeTable{
width: 100%;
}
JavaScript
// declare a module
var myApp = this.angular.module('myApp', []);
// declare a controller
myApp.controller('TimerCtrl', function ($scope) {
$scope.timer = null;
$scope.msg = 'Timer is not running.';
$scope.count = 0;
//Run this function when the 'Start Timer' button has been clicked.
$scope.startTimer = function(){
//Kill the timer to prevent a second function to be attach to the timer variable
$scope.stopTimer();
$scope.msg = 'Timer is running';
//Create a Timer that will execute the function $scope.update() every 100 milliseconds
$scope.timer = setInterval($scope.update, 1000);
}
//Run this function when the 'Stop and Reset Timer' button has been clicked.
$scope.stopTimer = function(){
clearInterval($scope.timer);
$scope.count = 0;
$scope.msg = 'Timer is not running.';
}
$scope.update = function(){
//Update the variable count
$scope.count++;
//Force the view to refresh and update accordingly
$scope.$apply();
}
});