johanson
johanson

Reputation: 119

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

Upvotes: 1

Views: 2355

Answers (3)

Jayrag Pareek
Jayrag Pareek

Reputation: 374

Try this:

var app = angular.module("myApp",[]);
var controllers = {};
app.controller(controllers);
app.filter('secondsToDateTime', [function () {
    return function (seconds) {
        return new Date(1970, 0, 1).setSeconds(seconds);
    };
}]);
controllers.StopWatchController = ['$scope', '$timeout',function ($scope, $timeout){
     $scope.seconds = 0;
     $scope.running = false;
     
     $scope.StartStopwatch = function () {       
        if (!$scope.running) {
          $scope.running = true;
          $scope.timer();
          }
     }
     
     $scope.StopStopwatch = function () {         
        $scope.running = false;
     }
     
      $scope.ClearStopwatch = function () {
        $scope.running = false; 
        $scope.seconds = 0;
     }
     
     $scope.timer = function () {
          if ($scope.running) {
              timeoutId = $timeout(function () {
                  $scope.updateTime();
                  $scope.timer();
              }, 1000);
          }
      }
      
     $scope.updateTime = function () {
          $scope.seconds++;
      }
}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div class="" ng-app="myApp" ng-controller="StopWatchController">
    <h2>{{seconds | secondsToDateTime | date:'HH:mm:ss'}}</h2>
    <button type="button" data-ng-click="StartStopwatch()">Start</button>
    <button type="button" data-ng-click="StopStopwatch()">Stop</button>
    <button type="button" data-ng-click="ClearStopwatch()">CLEAR</button>
</div>

Upvotes: 0

Felipe Anselmo
Felipe Anselmo

Reputation: 126

With instances new Date you can make a cleaner code as I did. This function is recursive and called with a interval of 1000ms, so each second it will refresh in your browser. Obs: the prefix vm is the controller var vm = this;

    vm.inicialDate = undefined;
    vm.stopWatch = '00:00:00';

    vm.tick = function() {
        if(vm.inicialDate) {
            var dateNow = Date.now();
            var timezone = new Date().getTimezoneOffset();

            vm.stopWatch = new Date(new Date(dateNow).getTime() - new Date(vm.inicialDate).getTime());
            vm.stopWatch.setMinutes(vm.stopWatch.getMinutes() + timezone);
        }
        $timeout(vm.tick, 1000);
    };

    $timeout(vm.tick, 1000);

If you want to use another inicial date instead of Date.now() you can get from your server a DateTime and use this line:

vm.inicialDate = new Date(parseInt(response.data.InicialDate.substr(6)));

Easy to show in HTML:

<h3 ng-show="your condition" style="color: #8E0000">{{vm.stopWatch | date: 'HH:mm:ss'}}</h3>

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

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/

Upvotes: 3

Related Questions