【问题标题】:$timeout doesn't work AngularJs$timeout 不起作用
【发布时间】:2018-12-24 21:17:16
【问题描述】:

这是我的代码:

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 秒后不会超时,但就像每一刻一样。为什么? 提前谢谢解答!!!

【问题讨论】:

  • setTimeout(function () { },0);你可以用这个。

标签: angularjs timeout


【解决方案1】:

你在这里犯了一个微妙的错误。

您无需设置$timeout 以在5000 毫秒后调用getapi_url,而是通过执行以下操作立即调用getapi_url 方法:

$scope.getapi_url(n)

在这一行:

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

实际上你刚刚调用了两个函数,第一个是; $scope.getapi_url(n) 和第二个; $timeout().

如果您对您的代码进行以下调整,您的getapi_url 方法将在$timeout 5000 毫秒的周期过去后被调用:

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

【讨论】:

    【解决方案2】:

    AngularJS 的超时包装器的调用方式是:

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

    您需要传递一个函数处理程序或将匿名函数直接写入 fn,而不是调用该函数。

    用途:

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

    以 n 作为参数调用函数。

    或者直接写anon函数代替fn:

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

    【讨论】:

      【解决方案3】:

      试试

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-27
        • 2018-12-06
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        相关资源
        最近更新 更多