Enigma State Enigma State - 4 months ago 14
Javascript Question

angular js timer function not working on stop button

I am learning angular js now for that purpose i have written sample test application with angular Js using timer function init ...
when ever i run the app in browser i am able to start the counter and when i click on the stop button, I am not able to stop the timer
Below is my code for timer function ..

<!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>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('NameCtrl', ['$scope','$interval', function ($scope,$interval) {

var i = 0;
var timer;
$scope.message = "Div is Refreshed at " + i + "seconds";
$scope.starttimer = function(){

timer= $interval(function(){

$scope.message = "Div is Refreshed at " + i + "seconds";
i++;
},1000)
}
$scope.stoptimer = function(){

if(angular.isUndefined(timer)){
$interval.cancel(timer);
timer = 'undefined';
$scope.message = "Timer is killed";
}
}
}])
</script>
</head>

<body>
<div ng-controller="NameCtrl">
<input type="button" id="btnStart" ng-click="starttimer()" value="Start" />
<input type="button" id="btnStop" ng-click="stoptimer()" value="Stop"/>
{{message}}
</div>
</body>




Could any one please point me in right direction and the point where I am doing wrong in the above code to stop the timer..

Would any one please help on this ..

Answer

The condition in your if statement in the stoptimer function is missing a negation :

if(angular.isUndefined(timer)){

should be

if(!angular.isUndefined(timer)){