使用 SSE 检测 readyState 的变化

Gia*_*uck 5 javascript javascript-events server-sent-events

我正在使用 HTML5 Server-Sent 事件:

SSEUpdate = new EventSource("update.php");
Run Code Online (Sandbox Code Playgroud)

我想检测何时SSEUpdate.readyState发生变化。我试过了.onerror,但是当我使用时console.log(SSEUpdate.readyState),我总是得到0. 我想在readyState更改为2. 谢谢!

Gia*_*uck 2

我最终使用了轮询解决方案:

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

捕获时间最多需要 0.5 秒,但它可以完成工作。