1

Here is my code :

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>

After click getapi_url my $timeout doesn' timeout after 5 seconds, but like every moment. Why? Thanks for answers in advance!!!

1
  • setTimeout(function () { },0); You can use this. Commented Jul 17, 2018 at 8:48

3 Answers 3

3

The way to call AngularJS's timeout wrapper is:

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

You need to pass a function handler or write anon function directly to fn, instead, you are calling the function.

Use:

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

To call the function with passing n as a parameter.

Or write anon function directly instead fn:

$timeout(function(){
  $scope.getapi_url(n)
}, 5000);
Sign up to request clarification or add additional context in comments.

Comments

1

You are making a subtle mistake here.

Instead of setting up a $timeout to call getapi_url after 5000ms, you are instead immediatly calling the getapi_url method by doing this:

$scope.getapi_url(n)

on this line:

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

Effectivly you have just called two functions, the first being; $scope.getapi_url(n) and the second being; $timeout().

If you make the following adjustment to you code, your getapi_url method will be invoked once the $timeout period of 5000ms has lapsed:

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

Comments

0

try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.