Search code examples
javascriptangularjsmomentjsangular-moment

Stopwatch/countdown (00:00:00) format with Javascript


I have this code:

    function startStopwatch() {
        vm.lastTickTime = new Date();

        $interval.cancel(vm.timerPromise);
        vm.timerPromise = $interval(function() {
            var tickTime = new Date();
            var dateDiff = vm.lastTickTime.getTime() - tickTime.getTime();
            var secondsDiff = Math.abs(dateDiff / 1000);
            vm.secondsElapsed += Math.round(secondsDiff);
            vm.formattedSecondsElapsed = moment.duration(secondsElapsed, "seconds").format("HH:mm:ss");
            vm.lastTickTime = tickTime;
        }, 1000);
    }

It ticks seconds (int) since the 'play' button was hit on a stopwatch.

But the format is 01, 02.... up to 60 and then 01:01, 01:02, etc.

I'd like to format it as 00:00:00, incrementing the int. I've found answers for other programming languages but not JavaScript. Any help appreciated!


Solution

  • Borrowing from the answer provided by RJB, convert the algorithm to a filter:

    Filter

    app.filter('time', function() { 
        function isInt(n){
            return Number(n) === n && n % 1 === 0;
        }
        return function(val) {
            if (isInt(val))
                return new Date(null, null, null, null, null, val).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    
            return val;
        }
    });
    

    Usage

    app.controller('ctrl', function($scope) {
        $scope.seconds = 25251;
    });
    

    HTML

    <div ng-controller="ctrl">
          {{ seconds | time }}
    </div>
    

    Demo Plunker