Search code examples
androidj2v8

J2V8 for Android, context methods


I'm using J2V8 port for Android (https://github.com/eclipsesource/J2V8).

Is it possible to enable context methods (setInterval, setTimeout, ..)?

V8 runtime = V8.createV8Runtime("global");
runtime.executeIntegerScript("setInterval(function() { 
console.log(\"Hello\"); }, 1000)");

It fails with error: "ReferenceError: setInterval is not defined".

Or engines can execute only pure javascript?


Solution

  • V8 Engine can execute only pure javascript. But you mimic the same, by registering setTimeout method in the engine, when you get the call for this function, you can schedule. like following. But you have to use Executors.newSingleThreadScheduledExecutor()

    private var setTimeOutCallback: JavaCallback = JavaCallback { _, v8Array ->
        val v8Function = v8Array.getObject(0) as V8Function
        val time = v8Array.getInteger(1).toLong()
        val taskId = Random.nextInt(1000, 9999)
        val task = v8Executor.schedule({
            v8Function.call(runtime, null)
        }, time, TimeUnit.MILLISECONDS)
        taskId
    }