JSFiddle - React, Tailwind, and code Playground

by nsjithin

HTML

<div ng-controller="MyCtrl">{{time}}

    <button ng-click="stop()">Stop</button>
    <button ng-click="start()">Start again</button>

</div>

JavaScript

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope, $interval) {
    $scope.time = '120:59:58';
    $scope.status = 'running';
    
    $scope.stop = function(){
        $scope.status = 'stopped';
        if(angular.isDefined($scope.timer))
          {
            $interval.cancel($scope.timer);
            timer=undefined;
          }
    }
    $scope.start = function(){
        $scope.status = 'running';
        $scope.timer = $interval(function(){
            $scope.time = updateTime($scope.time);
        }, 1000);
    }
    
    $scope.$on('$destroy', function() {
      $scope.stop();
    });
    
    if($scope.status == 'running'){
        $scope.start();
    }
    else{
        $scope.stop();
    }
}

function updateTime(time){
    arr = time.split(':');
    arr[2]++;
    if(arr[2] > 59){
        arr[1]++;
        arr[2] = 0;
    }
    if(arr[1] > 59){
        arr[0]++;
        arr[1] = 0;
    }
    return arr.map(function(v){
        v = parseInt(v);
        return v < 10 ? '0' + v : v;
    }).join(':');
}