How to pass Server Sent Event object in setInterval(function(){…})

问题: I want to stop SSE after some interval and need to reconnect again. Using setInterval(function(){}) in JavaScript gives error: source.close(); // <<-- ERROR : obj...

问题:

I want to stop SSE after some interval and need to reconnect again.

Using setInterval(function(){}) in JavaScript gives error:

source.close(); // <<-- ERROR : object is not defined

Can anyone guide me for solution please?

<script>

if(typeof(EventSource) !== "undefined"){

    var source = new EventSource("sse_server.php");

    // ReConnecting ST
    setInterval(function(){ 
        console.log("ReConnecting...");

        source.close(); // <<---------- ERROR : object is not defined

        var source = new EventSource("sse_server.php");
    }, 6000); 
    // ReConnecting EN

    source.addEventListener("response", function(event) {
         document.getElementById("result").innerHTML += "<p>" + event.data + "</p>";
    });

    source.addEventListener("message_status", function(event) {
         document.getElementById("result").innerHTML += "<p>" + event.data + "</p>";
    });

    source.onmessage = function(event) {

        var json = JSON.parse(event.data);

        if(json.category=="chat") {
            document.getElementById("result").innerHTML += "<p>"  + json.content.messageContent.messageText + "</p>";
        }else{
            document.getElementById("result").innerHTML += "<p>" + event.data + "</p>";
        } 

  };

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}


</script> 

回答1:

Look at this:

source.close(); // <<---------- ERROR : object is not defined
var source = new EventSource("sse_server.php");

You've defined a different variable with the same name in the scope of your function. Since you don't assign a value to it until the next line, it is undefined.

If you want to access the source from the wider scope inside the function, then don't reuse the name for a different variable inside the function.

If you want to overwrite the source in the wider variable, then remove var from the line inside the function so you use the existing variable and don't redeclare it in the local scope.

  • 发表于 2019-03-28 15:57
  • 阅读 ( 161 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除