From 2cb9e446292429e3e8e8d430a64228b10a93177a Mon Sep 17 00:00:00 2001 From: John Bintz Date: Wed, 14 Mar 2012 20:32:01 -0400 Subject: [PATCH] use a queue to run xhr jobs, so node isn't super slow --- lib/assets/javascripts/flowerbox.js.coffee | 36 +++++++++++++--------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/lib/assets/javascripts/flowerbox.js.coffee b/lib/assets/javascripts/flowerbox.js.coffee index d119667..c9f5f6c 100644 --- a/lib/assets/javascripts/flowerbox.js.coffee +++ b/lib/assets/javascripts/flowerbox.js.coffee @@ -7,25 +7,33 @@ Flowerbox = debug: false ping: -> Flowerbox.contact('ping') + working: false contact: (url, data...) -> if !Flowerbox.debug - attempts = 3 + Flowerbox.contactQueue ||= [] - doContact = -> - attempts -= 1 + Flowerbox.contactQueue.push([url, data]) + Flowerbox.workOffQueue() - try - xhr = new XMLHttpRequest() - xhr.open("POST", Flowerbox.baseUrl + url, false) - xhr.setRequestHeader("Accept", "application/json") - xhr.send(JSON.stringify(data)) - catch e - if attempts == 0 - throw e - else - doContact() + workOffQueue: -> + if !Flowerbox.working + Flowerbox.working = true + Flowerbox.doWorkOffQueue() + + doWorkOffQueue: -> + if Flowerbox.contactQueue.length > 0 + [ url, data ] = Flowerbox.contactQueue.shift() + + xhr = new XMLHttpRequest() + xhr.open("POST", Flowerbox.baseUrl + url, true) + xhr.setRequestHeader("Accept", "application/json") + xhr.onreadystatechange = -> + if @readyState == @DONE + Flowerbox.doWorkOffQueue() + xhr.send(JSON.stringify(data)) + else + Flowerbox.working = false - doContact() fail: ->