Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created May 26, 2010 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/415116 to your computer and use it in GitHub Desktop.
Save rwaldron/415116 to your computer and use it in GitHub Desktop.
<script src="event-source.js"></script>
document.addEventListener('DOMContentLoaded', function () {
var eventSrc = new EventSource('events.php');
eventSrc.addEventListener('open', function (event) {
console.log(event.type);
});
eventSrc.addEventListener('message', function (event) {
console.log(event.type);
console.log(event.data);
});
}, false);
<?php
header("Content-Type: text/event-stream\n\n");
// despite not having the while(true){}
// this seems to repeat pushing messages to the client
echo 'data: ' . time() . "\n";
?>
@thechriswalker
Copy link

The reason it repeats is that the connection is closed after the script terminates. The EventSource tries to reconnect, gets one message and the connection is terminated again. Repeat. Not really SSE but polling... looping and holding the connection open is the point of SSE, as it removes the HTTP overhead of the polling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment