Skip to content

Instantly share code, notes, and snippets.

@geronimod
Created January 20, 2017 19:46
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/663175b90fa8465fd89f8ccf95002075 to your computer and use it in GitHub Desktop.
Save geronimod/663175b90fa8465fd89f8ccf95002075 to your computer and use it in GitHub Desktop.
Status Polling Queue
class @StatusPollingQueue
constructor: () ->
@queue = []
@frequency = 3 * 1000 # 3 seconds
@interval = undefined
@failureLimit = 50
add: (url, options = {}) ->
return unless url
request = {
url: url,
params: {},
failures: 0
}
if options.params
request.params = options.params
if options.success
request.success = options.success
@queue.push(request)
processQueue: () ->
for request in @queue
error = (xhr, status, error) =>
request.failures += 1
if request.failures == @failureLimit
@queue.splice(@queue.indexOf(request), 1)
return
success = (response, status, xhr) =>
request.success?.call(this, response)
@queue.splice(@queue.indexOf(request), 1)
return
promise = $.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