I've seen answers on Stackoverflow mentioning how if a DOM element goes out of scope, its event listeners are automatically garbage collected. Is that also the case with non-DOM elements, such as EventSource?
Here's an example of what I mean:
function checkStatus(events) {
return function() {
if (events.readyState === EventSource.CLOSED) {
establishSSE(); // Is this fine?
} else {
setTimeout(checkStatus(events), 500);
}
}
}
function establishSSE() {
const events = new EventSource("/sse/" + sseID);
events.addEventListener("reply", sseReply);
events.addEventListener("refresh", sseRefresh);
setTimeout(checkStatus(events), 500);
}
establishSSE();
(I know I can use the onerror event. This is just an example)
In this case, would the previous event handlers be garbage collected when establishSSE was re-ran on line 4?
Edit:
I don't understand how these values can be garbage collected. For example, the following works:
function sseSubscribe() {
let events = new EventSource("/v1/sse/mySSEID");
events.addEventListener("message", sseHeartbeat);
events.addEventListener("reply", sseReply);
}
That is, new messages still cause the message and reply handlers to run.
But events is no longer accessible from anywhere within the program. So, shouldn't it have been garbage collected? It seems like EventSource is never garbage collected (unless maybe the connection is broken?)
Edit #2:
It seems that even if the event handlers are anonymous, like so:
function sseSubscribe() {
let events = new EventSource("/v1/sse/SSEID");
events.addEventListener("message", function() {
console.log("Heartbeat");
});
}
sseSubscribe();
This still works on my end. That is, Heartbeat is being logged into the console every 30 seconds (the interval my server sends them). This is despite events immediately going out of scope and being inaccessible anywhere else in the program.