NAME
JSPL::Context::Timeout - Call JavaScript with Timeouts
SYNOPSYS
use JSPL;
use JSPL::Context::Timeout;
...
$ctx->set_timeout(1);
# The folloing will throw a 'timeout' exception
$ctx->eval_wto(q|
var foo;
while(1) {
foo++
}
|);
DESCRIPTION
Up to SpiderMonkey v1.8.0 the documented way to control a runaway script was using a branch handler callback. JavaScript 1.8.1 (Gecko 1.9.1) introduced a new OperationCallback API and deprecated the branch handler API.
This module uses the new API to extend JSPL::Context. It adds hi-level methods to control how long a JavaScript operation can run.
INSTANCE METHODS
A "use JSPL::Context::Timeout" adds to class JSPL::Context the following:
- set_timeout($seconds, [ $callback ])
-
Set a timeout of $seconds in the context for timeout-aware operations. $seconds can be fractional.
$callback is an optional coderef which will get called if the timeout stops the execution of an script. If $callback is not given JSPL will cancel the execution and will throw an
Operation timeout
exception.See the "CALLBACKS" section below for a detailed discussion on the callback semantics.
- clear_timeout
-
Removes the operational timeout.
- eval_wto($source )
-
Like "eval" in JSPL::Context but be aware of the setted timeout if any.
- call_wto($name, @arguments)
-
Like "call" in JSPL::Context but be aware of the setted timeout if any.
CALLBACKS
If you do not set a callback JSPL will always cancel the execution of the script throwing an exception. Setting a callback allows you to have more control on the response to a timeout. The value returned by the callback will be checked and JSPL will act on it on the following way:
If you return a FALSE value, the script execution will be canceled. JSPL will not throw the Operation timeout
exception in this case.
If you return a TRUE value from the callback the execution of the script will be resumed. The return value taken as a number will be used to reset the timeout timer as follows:
- Any positive value
-
The timeout timer will be set to that value.
- -1
-
The timer will be set to the original value passed to the
set_timeout
call. - Any other value
-
The execution will be resumed but the timer won't be set. Effectively allowing the script to continue forever until completion.
In your callback you can freely re-enter JavaScript. The way you re-enter determines if a new timeout is activated or not.
Any non-trapped exceptions in the callback cancel the execution of the original script.
BUGS AND CAVEATS
The current implementation is based on alarm
and POSIX signaling. This module do not work in Win32 (yet).