I am using server sent events to query database for new records and display the events to the user
Here is my code
javascript
window.onload = function setDataSource() {
if (!!window.EventSource) {
var source = new EventSource("polling.php");
source.addEventListener("message", function(e) {
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
console.log("OPENED");
}, false);
source.addEventListener("error", function(e) {
console.log(e);
if (e.readyState == EventSource.CLOSED) {
console.log("CLOSED");
}
}, false); } else {}}
PHP
<?php
header("Content-Type: text/event-stream\n\n");
include_once dirname(__FILE__) . '/db.php';
session_start();
while (1) {
$response = getnewmessages();
echo 'data: Message '. json_encode1($response)."\n\n";
ob_flush();
flush();
sleep(5);
}
function getnewmessages ()
{
// query database and get new records.
}
It works fine and gets the new records for every 5 seconds. But the problem here is when I refresh the page manually,it takes so much time for page load.
When the page is loading, I can figure out that while loop still executes (at least thrice) and pauses the page. After so much time page starts loading normally. So my doubt is the while loop is pausing the execution
Can you please suggest me how to overcome this situation ? or How can I replace while loop?