in reply to displaying output at the correct moment

This is one case where disabling buffering on STDOUT can help you.

$| = 1;