Viral
Viral

Reputation: 1337

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 : 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> 

Upvotes: 1

Views: 505

Answers (1)

Quentin
Quentin

Reputation: 943614

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.

Upvotes: 1

Related Questions