如何在AngularJS中停止$ timeout?

时间:2017-07-17 09:33:52

标签: angularjs timeout

JS:

&

HTML:

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);
    };

我想在点击按钮后停止$ timeout。我的代码不起作用。 提前感谢您的回答!

1 个答案:

答案 0 :(得分:4)

您需要全局声明timer变量。试试这段代码。这有帮助

 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);
      };

    });