views:

41

answers:

2

How to terminate function/code (not entire page) when it takes some time, for example, more than 1 sec?

If Code > 1 Sec Then Terminate the code....

I found the command "Server.ScriptTimeou", but it stops the entire page instead of one command.

+1  A: 

You can run your function in a background process and start a timer simultaneously. Then abort the process if it runs more than 1 second.

If you want to run in the foreground then you probably have a loop somewhere that is taking a long time. Before you start running, save the current time. Then, somewhere in the middle of the loop, compare the saved time to the current time. When it hits one second, break out of the loop.

Eyal
A: 

The solution will depend on what you're doing. If you're calling a single function that you have no control over and that can sometimes run longer than 1 second or so, you're pretty much stuck with having to run that function on a background thread and then terminate the thread if it runs long.

If you're actually running a long loop, or some other code that you DO have control over, you could just note the current time before starting the process, and in the loop, check if you've run long, and if so, exit the loop.

Just depends.

drventure