Skip to content

Instantly share code, notes, and snippets.

@oskude
Created October 24, 2018 05:29
Show Gist options
  • Save oskude/7c694784fb26a76d6f0768fd827a5027 to your computer and use it in GitHub Desktop.
Save oskude/7c694784fb26a76d6f0768fd827a5027 to your computer and use it in GitHub Desktop.
function EventSource (url)
{
this.url = url;
this.offset = 0;
this.prefix = "data: ";
this._resetWorkaround();
}
EventSource.prototype._resetWorkaround = function () {
if (this.ajax) {
this.ajax.onreadystatechange = null;
this.ajax.abort();
}
this.offset = 0;
this.ajax = new XMLHttpRequest();
this.ajax.onreadystatechange = this._onchange.bind(this);
this.ajax.open("GET", this.url);
this.ajax.send();
}
EventSource.prototype._onchange = function () {
let msg = this.ajax.responseText.slice(this.offset);
this.offset += msg.length;
if (msg.startsWith(this.prefix)) {
let data = msg.replace(this.prefix, "");
this.onmessage({ data:data });
}
// we get high cpu and mem usage if we dont reset this...
if (this.offset >= 10000000) {
this._resetWorkaround();
}
}
EventSource.prototype.onmessage = function (msg) {
console.log("message", msg.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment