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.


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) {
  setTimeout(() => {
    console.log("connection closed");
  }, 10000)
} else {
  console.log("Sorry, your browser does not support server-sent events...");

Answered By – cSharp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published