Skip to content

Instantly share code, notes, and snippets.

@RHeijnen
Last active November 21, 2016 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RHeijnen/2aca425a57b7502bcea0256e16d01ecb to your computer and use it in GitHub Desktop.
Save RHeijnen/2aca425a57b7502bcea0256e16d01ecb to your computer and use it in GitHub Desktop.
Angular countdown timer function with callback
var _timerModule = angular.module("_timerModule", []);
_timerModule.factory('timerModule', function() {
return {
startTimer: function(durationTimeInSeconds, callback) {
var timer = durationTimeInSeconds, minutes, seconds;
var timeInterval = setInterval(function () {
/*
* Thanks to http://stackoverflow.com/users/2126755/robbmj for the formatting of time and the idea of a datetime'less timer
*/
// formatting
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
// log the count in console
console.log(minutes + ":" + seconds);
if (--timer < 0) {
// turn off interval and calls the callback function
clearInterval(timeInterval);
callback();
}
}, 1000); // run every 1000ms / 1 second
}
}
});
<html ng-app="testApp">
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-route.min.js"></script>
<script src="js/ng-app.js"></script>
<script src="js/_timerModule.js"></script>
<div ng-controller="MainCtrl" ng-cloak>
<button ng-click="timer()">
click me
</button>
</div>
</body>
</html>
'use strict';
var app = angular.module('testApp',['_timerModule']);
app.controller('MainCtrl', ['$scope', 'timerModule', function($scope, timeModule) {
$scope.helloWorld = function(){
console.log("eyoo");
}
$scope.timer = function(){
timerModule.startTimer(5 // timer duration
,$scope.helloWorld // callback function called when timer reaches 0
);
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment