Search code examples
javascriptangularjstimerdifferencestopwatch

angularjs calculate time difference between start time and current time


I'm trying to create something similar to a stop watch in an AngularJS app.

I've got a 'start' button that when clicked, the app will set a startTime variable which gets the current time and then I want another variable which updates every second and calculates the difference in seconds between the startTime variable and the current time which I can use as the stop watch value that's displayed to the user. I'll also need to be able to stop and restart the timer so I'd like the stop watch value to be stored in seconds so that I can easily start the timer at any number of seconds and resume the timer.

What's the simplest way of doing this?


Solution

  • Expanding on my comments above, something like this...

    var startTime = new Date();
    $scope.stopwatch = 0;
    
    $interval(function() {
        $scope.stopwatch = (new Date() - startTime) / 1000;
    }, 1000);
    

    and in your template

    <p>Seconds: {{ stopwatch }}</p>
    

    Bonus points for creating a filter for formatting the seconds in hh:mm:ss format.