Create a ticking clock using angularJS timeout service

In the past I have worked on lot of projects that required development of different type of clocks. I will not go into details into what those different types are. In this post I will show some code samples showing how to develop a very simple using angularJS.

If you have ever implement a user interface that needed to display a ticking clock in your web application, then you are very familiar with native java script functions like setTimeout and setInterval. angularJS wraps setTimeout in a service named as $timeout and hides nitty-gritty details from you.

Since I am going to be doing lot of date and time manipulations I am using moment library to do all the heavy lifting for me. I will strongly recommend using that library if your application does lot of time calendar, date and time manipulations.

Let's look at the simple code that I wrote that shows the clock as shown above.

<div class="portalclocks">
   <div ng-controller="PortalClockController">
    <i class="fa fa-clock-o white"></i> {{currentTime|displaydate}}
   </div>
</div>

<script>
var SchedulerDashboard = angular.module("SchedulerDashboardApp", []);
SchedulerDashboard.filter('displaydate', function() {
    return function (input, tz) {
        return input.format('MMM Do, YYYY - hh:mm:ss A');
    };
});
SchedulerDashboard.controller("PortalClockController", [
    '$scope', '$timeout', '$http', function ($scope, $timeout, $http) {
        $scope.currentTime = moment();
        var tick = function() {
            $scope.currentTime = moment();
            $timeout(tick, 1000);
        }
        $timeout(tick, 1000);
    }
]);
</script>

angularJS Controller

As you can see following best practices, the implementation has been split into controller and filter. PortalClockController has been passed $timeout service as dependency. This $timeout service is being used to execute tick function every 1s. You will notice that I have set moment object to property of $scope. It is as simple as it gets.

angularJS Filter

Controller's job is not to act as rendering engine. All the UI manipulations and formatting are done in a filter. As you can see that in HTML I have used {{currentTime|displaydate}} directive. What this means is that out put from my currentTime action will get passed on to displaydate filter. As you can see that in displaydate filter method I have second parameter as well. I am not using it in this sample. But this is where I am passing time zone information in case the time needs to be displayed in certain time zone.

This is all that you will need to implement a very simple ticking clock in your web application using angularJS.

Search

Social

Weather

25.2 °C / 77.4 °F

weather conditions Clear

Monthly Posts

Blog Tags