Skip to content

Instantly share code, notes, and snippets.

@hmbilal
Last active June 18, 2019 15:05
Show Gist options
  • Save hmbilal/e317f581a49c2744731f to your computer and use it in GitHub Desktop.
Save hmbilal/e317f581a49c2744731f to your computer and use it in GitHub Desktop.
Long polling service in AngularJS

Then in your controller, inject $polling and start polling like this.

General use

$polling.startPolling({name_of_this_polling}, {url_to_fetch_data_from}, {time_in_milli_seconds}, {callback});

Example,

$polling.startPolling('fetchNotifications', 'http://localserver.local/fetch/notifications', 10000, $scope.processData);

To stop a polling

$polling.stopPolling('fetchNotifications');

/**
* Created by bilal on 5/1/15.
*/
(function () {
'use strict';
var pollingService = angular.module("services.polling", []);
pollingService
.factory('$polling', function ($http) {
var defaultPollingTime = 10000;
var polls = [];
return {
startPolling: function (name, url, pollingTime, callback) {
if(!polls[name]) {
var poller = function () {
return $http.get(url).then(function (response) {
callback(response);
});
}
}
poller();
polls[name] = setInterval(poller, pollingTime || defaultPollingTime);
},
stopPolling: function (name) {
clearInterval(polls[name]);
delete polls[name];
}
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment