I am currently using an eventsource to have a list of real time notifications. But for no reason, this eventsource crashes for no reason, fortunately I have a function to reconnect it but, I can’t understand why it crashes and I don’t know how to get details (code, message..) of the “onerror” event. Here is my code:
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
function debounce(func, wait) {
var timeout;
var waitFunc;
return function() {
if (isFunction(wait)) {
waitFunc = wait;
} else {
waitFunc = function() {
return wait
};
}
var context = this,
args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, waitFunc());
};
}
// reconnectFrequencySeconds doubles every retry
var reconnectFrequencySeconds = 1;
var evtSource;
var is_deconnected = 0;
var is_first_connected = 0;
var reconnectFunc = debounce(function() {
is_deconnected = 1;
setupEventSource();
// Double every attempt to avoid overwhelming server
reconnectFrequencySeconds *= 2;
// Max out at ~1 minute as a compromise between user experience and server load
if (reconnectFrequencySeconds >= 64) {
reconnectFrequencySeconds = 64;
}
}, function() {
return reconnectFrequencySeconds * 1000
});
var notif_compt = 0;
var show_notif_compt = 0;
function setupEventSource() {
document.getElementById("notifs").innerHTML ="Loading";
evtSource = new EventSource("http://express-eventsource.herokuapp.com/events");
evtSource.addEventListener("data", function(event) {
console.log("Data from server: "+JSON.parse(event.data).data);
document.getElementById("notifs").innerHTML = JSON.parse(event.data).data;
if(JSON.parse(event.data).data == "the end") {
console.log("Reloading...");
evtSource.close();
reconnectFunc();
}
});
evtSource.onopen = function(e) {
console.log('Connected to server.')
// Reset reconnect frequency upon successful connection
reconnectFrequencySeconds = 1;
};
evtSource.onerror = function(e) {
evtSource.close();
console.error(e);
console.error(evtSource);
console.error(evtSource.readystate); // return undefined
reconnectFunc();
};
}
setupEventSource();
window.onbeforeunload = () => {
evtSource.close();
};
<h1>Hi, User123</h1>
<span>Notification number(random): <div id="notifs">Loading</div> </span>