Check out this Sitepoint Forum Post that describes the solution.
Basically, once the while loop breaks, you're done!
Here's the full thread that describes using an AJAX poll to detect when the download is complete: http://www.sitepoint.com/forums/showthread.php?t=618233