Reputation: 14429
I have a simple controller that runs an ajax call. What is the most optimal running this ajax call every 15 seconds instead of just once. And how do I also stop the call?
myApp.controller('myCntrl', function($window,$scope,$http,$routeParams,$location) {
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
console.log(data)
})
})
Upvotes: 0
Views: 1405
Reputation: 4329
function httpCall (){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
if(data == "expectedData") //condition to stop recursive ajax.
$tiemout(httpCall, 15000);
})
}
Upvotes: 4
Reputation: 5466
You can use $interval
service and stop it at an event as cancel(promise)
eg:
var promo = $interval(function(){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
console.log(data)
})
},1500);
clear interval as:
$interval.cancel(promo)
Upvotes: 3
Reputation: 136174
You could do it just by using $interval
var ajaxCall = function(){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
//on some condition
if(data.length == 0) //just for demonstration..you could add your own condition.
$interval.cancel(interval); //this is to cancel interval
console.log(data)
})
}
var interval = $interval(ajaxCall,15000)
Upvotes: 1