phoboslab / JavaScriptCore-iOS

Apple's JavaScript Engine, with modified project files for iOS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how to stop evaluate script

kingswords opened this issue · comments

I want to stop evaluate script when running JSEvaluateScript function,
How can I do this?

You could set an execution time limit with JSContextGroupSetExecutionTimeLimit. It's not public, so you need to declare the method somewhere in your code.

Why do you need this? Maybe there are better ways to handle this.

Background:When I run a for loop,there's a lot of the code inside the loop, it probably will run 10 minutes, I want to stop execute it at any time. @phoboslab

Why don't you divide the loop into smaller chunks of work that will take a few milliseconds each and schedule execution of each chunk with setTimeout or setInterval? This way you can stop the execution simply by not scheduling the next chunk.

commented

@kingswords have you got a solution? I need to stop it too.

@kingswords JSContextGroupSetExecutionTimeLimit works fine
note you need to call it again in your callback before you return false, otherwise the callback will never get called later.

commented

@kingswords JSContextGroupSetExecutionTimeLimit works fine
note you need to call it again in your callback before you return false, otherwise the callback will never get called later.

@laoyur Hi, I tried that way, but it didn't work, do you have any idea? Appreciate it!
My code:

int extendTerminateCallbackCalled = 0;
static bool extendTerminateCallback(JSContextRef ctx, void *context)
{
    NSLog(@">>>>>>>>>>>>>>>>>>>>> aaaaaa 1111111");
    extendTerminateCallbackCalled++;
    if (extendTerminateCallbackCalled == 2) {
        JSContextGroupRef contextGroup = JSContextGetGroup(ctx);
        JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
        NSLog(@">>>>>>>>>>>>>>>>>>>>> 2222222");
        return false;
    }
    return true;
}

+ (void)stop
{
    if (!_context) return;

    NSLog(@">>>>>>>>>>>>>>>>>>>>> bbbbbbbbb");

    // Doesn't work
    JSGlobalContextRef ref = [_context JSGlobalContextRef];
    JSContextGroupRef contextGroup = JSContextGetGroup(ref);
    JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);

    NSLog(@">>>>>>>>>>>>>>>>>>>>> ccccccc");
    // _context.exception = [JSValue valueWithNewErrorFromMessage:@"stopplaying" inContext:[JSEngine context]];
}