I would like to stop the countdown when the stop timer is pressed. Im not sure why this is not working. I have a simple jsfiddle set up here.
CODE
View
<div ng-app="timerApp" ng-controller="timerController">
<h4>Time Remaining: {{countdown}}</h4>
<button ng-click="startTimer()">Start Timer</button>
<button ng-click="stopTimer()">Stop Timer</button>
</div>
Controller
angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval', function ($scope, $interval) {
var timer;
var time = 10;
$scope.countdown = time;
$scope.stopTimer = function() {
$interval.cancel(timer);
};
$scope.startTimer = function() {
timer = $interval(function() {
$scope.countdown--;
}, 1000, time).then(function() {
$scope.countdown = time;
});
};
}]);
The AngularJS $interval makes use of the JavaScript setInterval method and works in the exact same way. Just like the JavaScript setInterval method, we can also Start, Stop and Cancel (Destroy) the AngularJS $interval function.
The $interval and $timeout is angular wrapper of setTimeout and setInterval JavaScript function.This angularjs tutorial help to create simple example of timer services timeout and interval, Both timer services are belongs to window object. Where Do We Use $timeout and $interval?
The $interval function can be cancelled by making use of its cancel method which accepts the object of the $interval function to be cancelled.
delay : Delay in millisecond to execute function. invokeApply : If true then invoke fn within the $apply block. Pass : Additional parameters to the executed function. We will create simple angularjs example to understand $timeout service using a method.We will create a method that will show ‘Hello’ message into console and execute after 2 sec.
The problem is call then
returns a new promise than the one returned by the $interval
which is required by the $interval.cancel()
method
angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
function($scope, $interval) {
var timer;
var time = 10;
$scope.countdown = time;
$scope.stopTimer = function() {
$interval.cancel(timer);
};
$scope.startTimer = function() {
timer = $interval(function() {
$scope.countdown--;
}, 1000, time);
timer.then(function() {
$scope.countdown = time;
});
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="timerApp" ng-controller="timerController">
<h4>Time Remaining: {{countdown}}</h4>
<button ng-click="startTimer()">Start Timer</button>
<button ng-click="stopTimer()">Stop Timer</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With