Created
September 4, 2010 15:23
-
-
Save dtinth/565267 to your computer and use it in GitHub Desktop.
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
// undeclared function you need to declare: | |
// cb(data): fired when new data from the stream is available. | |
// data is the updated line. use JSON.parse to parse data. | |
// hungup(): fired when the user stream is disconnected. | |
// this function needs to handle it. maybe retry or display error. | |
// undeclared variables you need to declare. | |
// url: user stream's url endpoint. | |
var xh = new XMLHttpRequest(); | |
var llen = 0; | |
var ltime = 0; | |
var buffer = ''; | |
var itvid; | |
var hungup = false; | |
function rsc() { | |
if (xh.readyState == 4) { | |
hangup (); | |
} | |
} | |
function hangup() { | |
if (!hungup) { | |
window.clearTimeout (itvid); | |
hung (); | |
} | |
hungup = true; | |
} | |
function line(data) { | |
ltime = new Date().getTime(); | |
if (data == '') { | |
return; | |
} | |
cb (data); | |
} | |
function itv() { | |
if (new Date().getTime() - ltime > 90000) { | |
hangup (); | |
xh.abort (); | |
} | |
if (llen != xh.responseText.length) { | |
buffer += xh.responseText.substr(llen); | |
var npos = buffer.indexOf('\n'); | |
while (npos > -1) { | |
line (buffer.substr(0, npos)); | |
buffer = buffer.substr(npos + 1); | |
npos = buffer.indexOf('\n'); | |
} | |
llen = xh.responseText.length; | |
} | |
} | |
xh.open ('GET', url, true); | |
xh.onreadystatechange = rsc; | |
xh.send (''); | |
ltime = new Date().getTime(); | |
itvid = window.setInterval (itv, 100); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oops! I mean "hung()" instead of "hungup()". Hungup is a variable to keep track of the state. My bad~