Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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 click button. My code don't work. Thanks for answers in advance!

like image 529
bafix2203 Avatar asked Mar 04 '26 07:03

bafix2203


1 Answers

you need to declare timer variable globally. try this code. does this 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);
      };

    });
like image 97
Shailesh Ladumor Avatar answered Mar 07 '26 08:03

Shailesh Ladumor