How to wait for a WebSocket's readyState to change

后端 未结 9 2329
梦如初夏
梦如初夏 2020-11-30 00:54

I\'m trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 00:56

    In my use case, I wanted to show an error on screen if the connection fails.

    let $connectionError = document.getElementById("connection-error");
    
    setTimeout( () => {
      if (ws.readyState !== 1) {
        $connectionError.classList.add( "show" );
      }
    }, 100 );  // ms
    

    Note that in Safari (9.1.2) no error event gets fired - otherwise I would have placed this in the error handler.

提交回复
热议问题