Reputation: 1056
Recently I have been struggling with Long polling in angularJS. I had this code working in the past:
function longPulling(){
$.ajax({
type: "GET",
url: "someScript.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
appendMessage("new", data);
setTimeout(
longPulling,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
appendMessage("error", textStatus + " (" + errorThrown + ")");
setTimeout(
longPulling,
15000);
}
});
};
$(document).ready(function(){
longPulling();
});
And this worked when I used some php script. Next I wanted this to work in angular and I created the following:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
}, function errorCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
});
};
$scope.longPolling();
}
For testing purposes I did not include a url and checked the console for 404 errors. I used $interval to set 5 second intervals, the problem with this was that it created multiple threads running the interval (looked like it, correct me if im wrong). So I browsed some StackOverflow topics and tried to apply one of the solutions to my code, looking like this:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
var promise;
$scope.start = function() {
$scope.stop();
promise = $interval( $scope.longPolling(), 5000);
};
$scope.stop = function() {
$interval.cancel(promise);
};
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.start();
}, function errorCallback(response) {
$scope.start();
});
};
$scope.start();
}
The problem with this one is that the interval just doesn't work, it lookes likes its just a regular recursive method that runs thousands of times per seconds. I need to find a solution where I can perform long polling to some url withouth duplicate threads. How can I do this?
Upvotes: 0
Views: 285
Reputation: 7900
Omit the parenthesis and you are fine:
promise = $interval( $scope.longPolling, 5000);
The parenthesis mean "call this function right the way". What $interval
expects is a callback, not the result of the function call.
Upvotes: 1