iOS implemention of “window.setTimeout” with JavascriptCore

血红的双手。 提交于 2019-12-04 06:47:25

I ended up adding setTimeout to a specific JavaScriptCore context like this, and it worked well:

JSVirtualMachine *vm = [[JSVirtualMachine alloc] init];
JSContext *context = [[JSContext alloc] initWithVirtualMachine: vm];

// Add setTimout
context[@"setTimeout"] = ^(JSValue* function, JSValue* timeout) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([timeout toInt32] * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [function callWithArguments:@[]];
    });
};

In my case, this allowed me to use cljs.core.async/timeout inside of JavaScriptCore.

Don't hang onto a JSContextRefs except for the one you created with JSGlobalContextCreate

Specifically, this is bad:

jsEngine.timeoutCtx =  ctx;
....
JSObjectCallAsFunction(timeoutCtx

Instead of saving ctx, pass your global context to JSObjectCallAsFunction.

You must JSValueProtect any values you want to keep around longer than your callback

The JavaScriptCore garbage collector could run anytime you call a JavaScriptCore function. In your example, the anonymous function created as the single argument to setTimeout is not referenced by anything in JavaScript, which means it could be garbage collected at any point in time after the call to setTimeout completes. setTimeout must therefore JSValueProtect the function to tell JavaScriptCore not to collect it. After you invoke the function with JSObjectCallAsFunction you should then JSValueUnprotect it, otherwise that anonymous function will hang around in memory until the global context is destroyed.

Bonus: you usually should return JSValueMakeUndefined(ctx) if you don't want to return anything from a function

JSValueMakeNull(ctx) is a different than undefined. My general rule is to return JSValueMakeUndefined if I would return void in Objective-C and JSValueMakeNull if I would return a nil object. However, if you want to implement setTimeout like the window object then it needs to return an ID/handle that can be passed to clearTimeout to cancel the timer.

For registered iOS developer, take a look at the new video about javascript core from wwdc 2013 called "Integrating JavaScript into Native Apps". You will find there the solution for newest iOS version.

My alternative solution, for the current iOS version, was to make a global array in JSC for storing objects that should be protected from garbage collector. So, you have control to pop variable from array when it is not needed any more.

I have implemented setTimout, setInterval and clearTimeout on Swift to solve this problem. Usually, the examples show only the setTimeout function without the option to use clearTimeout. If you are using JS dependencies, there's a big chance that you are going to need the clearTimeout and setInterval functions as well.

import Foundation
import JavaScriptCore

let timerJSSharedInstance = TimerJS()

@objc protocol TimerJSExport : JSExport {

    func setTimeout(_ callback : JSValue,_ ms : Double) -> String

    func clearTimeout(_ identifier: String)

    func setInterval(_ callback : JSValue,_ ms : Double) -> String

}

// Custom class must inherit from `NSObject`
@objc class TimerJS: NSObject, TimerJSExport {
    var timers = [String: Timer]()

    static func registerInto(jsContext: JSContext, forKeyedSubscript: String = "timerJS") {
        jsContext.setObject(timerJSSharedInstance,
                            forKeyedSubscript: forKeyedSubscript as (NSCopying & NSObjectProtocol))
        jsContext.evaluateScript(
            "function setTimeout(callback, ms) {" +
            "    return timerJS.setTimeout(callback, ms)" +
            "}" +
            "function clearTimeout(indentifier) {" +
            "    timerJS.clearTimeout(indentifier)" +
            "}" +
            "function setInterval(callback, ms) {" +
            "    return timerJS.setInterval(callback, ms)" +
            "}"
        )       
    }

    func clearTimeout(_ identifier: String) {
        let timer = timers.removeValue(forKey: identifier)

        timer?.invalidate()
    }


    func setInterval(_ callback: JSValue,_ ms: Double) -> String {
        return createTimer(callback: callback, ms: ms, repeats: true)
    }

    func setTimeout(_ callback: JSValue, _ ms: Double) -> String {
        return createTimer(callback: callback, ms: ms , repeats: false)
    }

    func createTimer(callback: JSValue, ms: Double, repeats : Bool) -> String {
        let timeInterval  = ms/1000.0

        let uuid = NSUUID().uuidString

        // make sure that we are queueing it all in the same executable queue...
        // JS calls are getting lost if the queue is not specified... that's what we believe... ;)
        DispatchQueue.main.async(execute: {
            let timer = Timer.scheduledTimer(timeInterval: timeInterval,
                                             target: self,
                                             selector: #selector(self.callJsCallback),
                                             userInfo: callback,
                                             repeats: repeats)
            self.timers[uuid] = timer
        })


        return uuid
    }

Usage Example:

jsContext = JSContext()
TimerJS.registerInto(jsContext: jsContext)

I hope that helps. :)

Based on @ninjudd's answer here is what I did in swift

    let setTimeout: @objc_block (JSValue, Int) -> Void = {
        [weak self] (cb, wait) in

        let callback = cb as JSValue

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(wait) * NSEC_PER_MSEC)), dispatch_get_main_queue(), { () -> Void in
            callback.callWithArguments([])
        })
    }
    context.setObject(unsafeBitCast(setTimeout, AnyObject.self), forKeyedSubscript: "setTimeout")

Here is my two cents.

I think there is no need to keep a reference to context in _setTimeout. You can leverage the global context to invoke a timer function later.

You should use JSValueProtect to protect jsEngine.timeoutFunc from GC in _setTimeout. Otherwise it can turn to an invalid reference and cause crash later.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!