有时应该强制停止正在评估的脚本,但我找不到实现的方法。有人指出 JSContextGroupSetExecutionTimeLimit
可能会有用,但在我的测试中却没用,有人能帮忙吗?
另一个参考。https:/github.comphoboslabJavaScriptCore-iOSissues14。
我的代码。
int extendTerminateCallbackCalled = 0;
static bool extendTerminateCallback(JSContextRef ctx, void *context)
{
extendTerminateCallbackCalled++;
if (extendTerminateCallbackCalled == 2) {
JSContextGroupRef contextGroup = JSContextGetGroup(ctx);
JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
return false;
}
return true;
}
+ (void)stop
{
JSGlobalContextRef ref = [_context JSGlobalContextRef];
JSContextGroupRef contextGroup = JSContextGetGroup(ref);
JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
}
下面是一个可能的方法的想法
+ (void)stop
{
JSContext *context = [JSContext currentContext]; // or whichever your
// set property of JS global object to specific know value
// that should be checked inside JS code regularly during
// long operations and interrupt self execution
context[@"externallyCancelled"] = @(YES);
}