PHP Server Sent Event overload on While loop

I’m creating an infopage for work that updates “live”.

Now i came across Server Sent Events.

I managed to put data on the screen but the update was every 3 seconds.
(After looking online it appears i created a disconnect and the default retry time was 3 seconds)

So i found a sollution that in theory should work but when putting it live, it creates an overload on the server side.

<?php

        // make session read-only
        session_start();
        session_write_close();

        // disable default disconnect checks
        ignore_user_abort(true);

        // set headers for stream
        header("Content-Type: text/event-stream");
        header("Cache-Control: no-cache");
        header("Access-Control-Allow-Origin: *");

        // Is this a new stream or an existing one?
        $lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
        if ($lastEventId == 0) {
            $lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
        }

        echo ":" . str_repeat(" ", 2048) . "n"; // 2 kB padding for IE
        echo "retry: 1000n";

        // start stream
        while(true){
            if(connection_aborted()){
                exit();
            } else{

                // here you will want to get the latest event id you have created on the server, but for now we will increment and force an update
                $latestEventId = $lastEventId+1;

                if($lastEventId < $latestEventId){
                    echo "id: " . $latestEventId . "n";
                    echo "data: Howdy (".$latestEventId.") nn";
                    $lastEventId = $latestEventId;
                    ob_flush();
                    flush();
                } else{
                    // no new data to send
                    echo ": heartbeatnn";
                    ob_flush();
                    flush();
                }
            }
    
            // 2 second sleep then carry on
            sleep(1);
        }
        
?>

It appears that the while(true) loop is the problem …

Unfortunatly i couldn’t find the correct way to use Server Side events with a connection that stays open.

Is there someone that knows a sollution for this?

i tried using this script without while loop (which works) BUT thats because the client side keeps reconnecting after every 3 seconds, so basically the connection opens, closes, opens, closes