Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect change of readyState with SSE

I am using HTML5 Server-Sent events:

SSEUpdate = new EventSource("update.php");

I want to detect when SSEUpdate.readyState changes. I've tried .onerror, but when I use console.log(SSEUpdate.readyState), I always get 0. I want to run my function when readyState changes to 2.

like image 664
GiantDuck Avatar asked Oct 31 '22 19:10

GiantDuck


1 Answers

I ended up using a polling solution:

var SSECheck = setInterval(function() {
    if (SSEUpdate.readyState == 2) {
        clearInterval(SSECheck);
        // call to fn to restart sse
    }
}, 500);

Takes up to 0.5s to capture, but it does the job.

like image 70
GiantDuck Avatar answered Nov 12 '22 12:11

GiantDuck