How do I stop $ timeout in AngularJS?
JS:
var vm = this;
vm.loadNames = function () {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
$timeout(vm.loadNames, 5000);
});
};
var timer = $timeout(vm.loadNames, 5000);
$scope.canceltime = function(){
$timeout.cancel(timer);
};
HTML:
<button ng-click="canceltime()"></button>
I want to stop $ timeout after button click. My code is not working. Thanks for the answers in advance!
+3
source to share
1 answer
you need to declare the variable timer
globally. try this code. does it help
var vm = this;
var timer;
vm.loadNames = function () {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
timer = $timeout(vm.loadNames, 5000);
});
};
$scope.canceltime = function(){
$timeout.cancel(timer);
};
$scope.mouseout = function(){
timer = $timeout(function () {
$scope.show = false;
}, 2000);
};
});
+4
source to share