<?php declare(strict_types=1);

final class TimedBuffer
{
	private $buffer = '';

	private $intervalMs;

	private $startTime;

	public function __construct( int $intervalMs )
	{
		$this->startTime  = microtime( true );
		$this->intervalMs = $intervalMs;
	}

	public function write( string $content ) : void
	{
		$this->buffer .= $content;
	}

	public function flush() : void
	{
		$compareTime = microtime( true ) - $this->intervalMs;

		if ( $compareTime < $this->startTime )
		{
			return;
		}

		# Wherever you want to flush the buffer to goes here
		echo $this->buffer;
		flush();

		$this->buffer    = '';
		$this->startTime = $compareTime;
	}
}

$timedBuffer = new TimedBuffer( 500 );

$passThroughCallback = function ( string $buffer ) use ( $timedBuffer )
{
	$timedBuffer->write( $buffer );
	$timedBuffer->flush();
};