代码之家  ›  专栏  ›  技术社区  ›  bafix2203

$timeout不起作用AngularJS

  •  1
  • bafix2203  · 技术社区  · 6 年前

    这是我的代码:

    JS:

    var timer;
    $scope.getapi_url = function (n) {
        var url = n;
        $http({
                method: 'GET',
                url: url,
            })
            .then(function successCallback(data) {
                $scope.data = data.data;
                console.log($scope, data);
                timer = $timeout($scope.getapi_url(n), 5000); 
                // passing n if you don't want check n value on starting of function.
            }, function errorCallback(response) {
                $scope.errorBackend = true;
                console.log(response);
                console.log('error');
            });
    };
    

    HTML:

    <button class="btn btn-clear btn-sm" ng-click="getapi_url('myurl') ">Click!</button>
    

    单击后 getapi_url 我的 $timeout 不会在5秒后超时,但就像每一刻一样。为什么? 感谢您提前回答!!!!

    3 回复  |  直到 6 年前
        1
  •  3
  •   CodeSmith    6 年前

    $timeout([fn], [delay], [invokeApply], [Pass]);
    

    $timeout($scope.getapi_url, 5000, false, n); 
    

    $timeout(function(){
      $scope.getapi_url(n)
    }, 5000);
    
        2
  •  1
  •   Dacre Denny    6 年前

    $timeout getapi_url

    $scope.getapi_url(n)

    $timeout($scope.getapi_url(n), 5000)

    $timeout()

    function successCallback(data) {
    
        $scope.data = data.data;
        console.log($scope, data);
    
       // This is calling getapi_url immediately, at the point of creating your timeout
       // timer = $timeout($scope.getapi_url(n), 5000); 
    
       // You should do this instead
       timer = $timeout(function() {
            $scope.getapi_url(n);
       }, 5000);
    }
    
        3
  •  0
  •   holydragon    6 年前

    timer = $timeout(function(){ $scope.getapi_url(n)}, 5000);