I am using following code in one of my programs. It provides server-push to a HTML front-end.
Everything works as expected, but after some time of work (several days) the browser eats all the memory and the computer hangs and need to be restarted.
Is it possible my code leaks memory, or the problem is in the browser? I know that it is possible the bad JavaScript code to leak memory on some circumstances and as long as my JS skills are close to zero...
The code itself:
var keepAliveTimer = null;
function gotActivity() {
if (keepAliveTimer != null) clearTimeout(keepAliveTimer);
keepAliveTimer = setTimeout(connect, 3000);
}
function connect(){
gotActivity();
var source = new EventSource('/Events?');
source.onmessage =
function (event) {
var N = event.data.split("=");
var K=N.shift();
var H = "";
for (var i=0; i<N.length; i++) {
if (i>0) {H += "="};
H += N[i];
};
var el = document.getElementById(K);
if (el.hasAttribute("value")) {
el.value = H;
} else {
el.innerHTML = H;
};
};
};
connect();
This keep-alive timer mechanism was suggested in this answer.
EDIT1: Reading the source once again. When the created EventSource
object is released? In my understanding, exiting from connect()
the source
variable is destroyed and the EventSource object remains existing forever. The next call to connect()
will simply create another such object, without destroying the old one. Am I right?