title: How to stop Server-Sent Events
body: <p>Hello I have a javascript code that listens to a PHP code via Server-Sent Events, it is working well the response is sent from the server trough a loop and when the loop ends the Server-Sent Events stops however a few seconds after the script is again listening. how can I end the Server-Sent Events when the loop from the server side ends too? Thanks.</p>
  
  <p>JS :</p>
  
  <pre><code>var sse=new EventSource("data.php");
              sse.onmessage=function(event){
                  document.getElementById("map").innerHTML+=event.data;              
              };
  </code></pre>
  
  <p>PHP:</p>
  
  <pre><code>&lt;?php
  header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
  header('Cache-Control: no-cache');//disable caching of response
  
  $coordinates = [  
     [  
        "20:11",
        33.5731235,
        -7.6433045
     ],
     [  
        "20:11",
        33.5731054,
        -7.6432876
     ],
     [  
        "20:11",
        33.5731644,
        -7.6433304
     ]
  ];
  
  foreach($coordinates as $c){  
    echo "data: ".json_encode($c)."\n\n";
    ob_get_flush();
    flush();
    sleep(1);
  }
  </code></pre>