Last active
February 17, 2017 16:05
-
-
Save geronimod/2e232b59a1aa7065e60cc2c3b9b31201 to your computer and use it in GitHub Desktop.
Polling Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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