Skip to content

Instantly share code, notes, and snippets.

@geronimod
Last active February 17, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geronimod/2e232b59a1aa7065e60cc2c3b9b31201 to your computer and use it in GitHub Desktop.
Save geronimod/2e232b59a1aa7065e60cc2c3b9b31201 to your computer and use it in GitHub Desktop.
Polling Queue
class @PollingQueue
constructor: (opts) ->
opts || (opts = {})
@queue = {}
@frequency = opts.frequency || 3000 # 3 seconds
@interval = undefined
add: (url, options = {}) ->
return unless url
request = {
url: url,
params: {},
}
if options.params
request.params = options.params
if options.success
request.success = options.success
if options.stopPolling
request.stopPolling = options.stopPolling
# store by url to know to which one belongs the aja response
@queue[url] ||= []
@queue[url].push(request)
processQueue: () ->
for url, requests of @queue
@process(url, requests)
process: (url, requests) ->
error = (xhr, status, error) =>
for request in requests
@queue[request.url].splice(@queue[request.url].indexOf(request), 1)
return
success = (response, status, xhr) =>
for request in requests
request.success?.call(this, response)
if request.stopPolling && request.stopPolling(response)
@queue[request.url].splice(@queue[request.url].indexOf(request), 1)
return
for request in requests
$.ajax({
url: request.url,
data: request.params,
error: error,
success: success,
})
polling: () ->
@processQueue()
unless @interval
@interval = setInterval @polling.bind(@), @frequency
if @queue.length == 0
clearInterval @interval
@interval = undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment