2017-07-17 66 views
3

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> 

我想停下來點擊按鈕後,$超時。我的代碼不起作用。 感謝您提前給出答案!

回答

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

    }); 
+1

謝謝,你幫我 – bafix2203