Search code examples
angularjsstopwatch

AngularJs: How to make stopwatch in time format


I have number in $scope.number variable that is updating each second:
1
2
3
70....

how to get stopwatch with time format:
00:01
00:02
00:03
01:10


Solution

  • You could create a filter for this.

    angular.module('my-app').filter("timeFilter", function() {
        return function(number) {
            var seconds;
            var minutes;
            var hours;
    
            if (number < 60) {
                seconds = number;
            }
            else if (number >= 60 && number <= 3600) {
                minutes = Math.floor(number / 60);
                seconds = number % 60;
            }
            else {
                hours = Math.floor(number / 3600);
                minutes = Math.floor((number % 3600) / 60);
                seconds = Math.floor((number % 3600) % 60);
            }
            seconds = seconds < 10 ? "0" + seconds : seconds;
            minutes = minutes < 10 ? "0" + minutes : minutes;
            hours = hours < 10 ? "0" + hours: hours;
    
            return hours + ":" + minutes + ":" + seconds;
        }
    });
    

    Your controller might look something like this

    angular.module('my-app').controller('myController', ['$scope', '$interval',
    'TimeFilter', function($scope, $interval, TimeFilter) {
        $scope.number = 0;
    
        function updateNumber() {
            $scope.number++;
        });
    
        $interval(updateNumber, 1000);
    }]);
    

    In your view you'd want to attach two way data binding so the controller can update the value in the view, and the view can send the value back to the controller. We do this with ng-bind.

    To display a number as a filter, you can use the pipe character (|)

    <div ng-controller="myController" ng-bind="number">
      <p>{{number | timeFilter }</p>
    </div>
    

    02:13:20 should display

    Hope this helps

    Note: My syntax may not be entirely correct and if that's the case I apologize. However, you can also use this website as a guide

    https://docs.angularjs.org/api/ng/service/$interval

    Here is a working fiddle I found of a stopwatch. The credit does not go to me here.

    http://jsfiddle.net/joshkurz/5LCXU/