How can I check for live updates without using setInterval/timeout?

后端 未结 2 740
失恋的感觉
失恋的感觉 2020-12-31 12:13

Building a social network, I\'m trying to fetch live notifications. Currently, the site sends an AJAX request every few seconds using setInterval. It looks something like th

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 13:03

    You should use websockets. You can connect to the server and register onmessage handler. Whenever the server has anything to be send to client, your handler will get invoked. No timeout needed.

    Check for websocket support in your browser. As of now, only Chrome, Opera and Safari support them.

    if ('WebSocket' in window){
       /* WebSocket is supported. You can proceed with your code*/
    } else {
       /*WebSockets are not supported. Try a fallback method like long-polling etc*/
    }
    

    Connecting

    var connection = new WebSocket('ws://example.org:12345/myapp');
    

    Handlers

    connection.onopen = function(){
       console.log('Connection open!');
    }
    
    connection.onclose = function(){
       console.log('Connection closed');
    }
    
    connection.onmessage = function(e){
       var server_message = e.data;
       console.log(server_message);
    }
    

    Documentation: http://www.developerfusion.com/article/143158/an-introduction-to-websockets/

提交回复
热议问题