if the user disconnects the script keeps executing

to cancel execution in case of a really long loop or page, periodically test
if(connection_aborted()) die();

http://us.php.net/connection_aborted

to test periodically within a loop to limit cpu you might use modulus (php:%) up to a certain data size, depending which is more expensive, to do it each time, or every 15:

if( $i % 15 == 0 ){
if(connection_aborted()) die();
}

this is assuming a loop with index $i and up to 0.5 seconds per iteration, a particularly slow iteration in which case its worth doing an inexpensive test like this which probably contributes relatively small amount to that total, determined by 15 or by defining a $PAGE_ABORT_TIMEOUT and using a timer to test the timer with division to determine if it has exceeded the iteration level of $PAGE_ABORT_TIMEOUT:


$timer = $startTime-$currentTime;
if( ($timer / $PAGE_ABORT_TIMEOUT) >= 1 ) {
if(connection_aborted()) die();
$startTime=$currentTime;
}

again you might do this test outside of a loop, or you may restrict it with modulus which is likely less expensive. fine tuning is usually not a big deal but it depends on the size an frequency of access.

In php I recommend using mktime() to get the time, since its a nice integer value of seconds that can easily be devided by some interval size. Just search for php mktime to find out how to divide by various values to derive number of seconds, hours or minutes. There are many different ways to implement this!

in case of ASP something like

if i mod 15 = 0 then
if Not Response.IsClientConnected() then
Response.end
end if
end if

I’m sure there are alternative ways to trigger based on time rather than based on how slow the code will run to determine if a check is worth it or not. This is so rarely a problem that the script takes so long to finish executing and one is prevented from testing further but it comes up frequently enough that its nice to have a way to prevent it from going on until completion and take control simply by pressing your browsers stop button. This code is all untested, but researched while waiting for a script to timeout so I could load another page. I would bet you can find or implement comparable functions in just about any HTTP application. It would be nice to have something where from HTML5 page you can tell the server to cancel other requests from the same session although I would imagine this existing on the web server level or some way to “manage” each web request process. Most scripts finish too quickly to bother with canceling anyway but if users of a particular IP are locked down to one regular request at a time that gets canceled this can be very useful, especially if code you are testing ends up taking WAY longer than expected to execute. So set the $PAGE_ABORT_TIMEOUT timeout to whatever size break you would like to have whenever this happens :-D