in reply to Re^2: Keep running script but ending it to the browser
in thread Keep running script but ending it to the browser

Your first approach didn't look that bad (okay, I would suggest a sleep 5; instead of busy-waiting / saves some CPU). Anyway, the browser keeps waiting because it waits for further HTTP data on a still open TCP connection. If you can manage to close the connection before waiting to remove the file, shouldn't that fix the problem?
Another Idea: Unless the temporary GIFs must be removed immediately, why not let them live for a while until the next invocation of your program? At the end of your program use stat() to remove all of your GIFs from previous runs whose ctime is older than than the maximum lifespan. Alternatively, you can run a small daemon to keep the directory clean. Should work for low traffic scenarios.