Jeeva Jeeva - 4 months ago 6
HTML Question

The AnglularJS Interval Doesn't Pause if pressed the Interval(Continue btn) twice or more

I have a Time with Milliseconds continuously running using the AngularJS Interval Feature. I have created a Pause and Continue button. WHen the Pause button is hit it will trigger the AngularJS's Interval.cancel feature and if i click the continue button it will trigger the Interval Feature but the Problem is when i hit the Continue button twice or more and then hit the pause button it doesn't pause and the milliseconds keeps running but it does pause when the continue button is hit once. Below is the Screenshot of the UI. A Help is really Appreciated.

enter image description here

AngularJS Code

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date();

$scope.startInterval = function(){
$scope.flag = $interval(function(){
$scope.theTime = new Date();
}, 6);
}

$scope.stopInterval= function(){
if($scope.flag)
$interval.cancel($scope.flag);
}
// $scope.startInterval();
});


HTML code

<div class="col-lg-12 text-center" ng-app="myApp" ng-controller="myCtrl" >
<h3 ><b id="thetime"><span id="acttime" ng-mouseover="stopInterval()" ng-mouseleave="startInterval()" >{{theTime| date:'hh:mm:ss sss a'}}</span> <button class="btn btn-sm btn-success Start" ng-click="stopInterval()" style="margin-bottom: 70;"> Pause </button>
<button class="btn btn-sm btn-info Start" ng-click="startInterval()" style="margin-left: -92;margin-top: 25;"> Continue </button></b></h3>
</div>

Answer

Try this , its working

Make $scope.flag is undefined while timer is stop.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
  $scope.theTime = new Date();
  $scope.flag = 'undefined';
  $scope.startInterval = function(){
         if($scope.flag == 'undefined'){
         $scope.flag = $interval(function(){
                        $scope.theTime = new Date();
                    }, 6);
           }
    }

    $scope.stopInterval= function(){
       if(!angular.isUndefined($scope.flag)){
       $interval.cancel($scope.flag);
       $scope.flag = 'undefined';
         }
    }
   // $scope.startInterval();
});
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title>Angularjs</title>
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>


</head>

<body>
    <div ng-controller="myCtrl">
       <div class="col-lg-12 text-center" ng-app="myApp" ng-controller="myCtrl"   >
<h3 ><b id="thetime"><span id="acttime" ng-mouseover="stopInterval()" ng-mouseleave="startInterval()" >{{theTime| date:'hh:mm:ss sss a'}}</span> <button class="btn btn-sm btn-success Start" ng-click="stopInterval()" style="margin-bottom: 70;"> Pause </button>
 <button class="btn btn-sm btn-info Start" ng-click="startInterval()" style="margin-left: -92;margin-top: 25;"> Continue </button></b></h3>
</div>
    </div>
</body>

Comments