Reputation: 541
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!!!
Upvotes: 1
Views: 812
Reputation: 30360
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);
}
Upvotes: 1
Reputation: 3197
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);
Upvotes: 3