RJB
RJB

Reputation: 2103

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!

Upvotes: 1

Views: 1107

Answers (2)

Michael Kang
Michael Kang

Reputation: 52867

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

Upvotes: 2

RJB
RJB

Reputation: 2103

I'm going to undelete this because I think this is the best answer and I think it has academic value.

vm.durationElapsed = new Date(null, null, null, null, null, secondsElapsed).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

Answer found on: https://stackoverflow.com/a/12612778/1507899

Upvotes: 1

Related Questions