Srikanth Reddy
Srikanth Reddy

Reputation: 545

EventSource for fixed seconds in Javascript

I'm newbie to the feature of EventSource in javascript. As per my understanding the eventsource calls the api with stream content and gets the updates of data automatically without making any further calls. But I'm planning to make if possible to stop listening the response after 10 seconds from the EventSource. For Example in the below URL we can find the EventSource example, I want it to get stopped listening/fetching after 10 seconds.

https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_sse

Upvotes: 1

Views: 1167

Answers (1)

cSharp
cSharp

Reputation: 3159

You could use EventSource.close() method and call it in a setTimeout() such as follows (adapted from the linked W3Schools code):

if(typeof(EventSource) !== "undefined") {
  const source = new EventSource("demo_sse.php");
  source.onmessage = function(event) {
    console.log(event.data);
  };
  
  setTimeout(() => {
    source.close();
    console.log("connection closed");
  }, 10000)
  
} else {
  console.log("Sorry, your browser does not support server-sent events...");
}

Upvotes: 3

Related Questions