Skip to content Skip to sidebar Skip to footer

How To Run A Javascript Function Asynchronously, Without Using Settimeout?

its a server side Javascript (rhino engine), so setTimeout is not available. how to run a function asynchronously?

Solution 1:

You can use java.util.Timer and java.util.TimerTask to roll your own set/clear Timeout and set/clear Interval functions:

varsetTimeout,
    clearTimeout,
    setInterval,
    clearInterval;

(function () {
    var timer = new java.util.Timer();
    var counter = 1; 
    var ids = {};

    setTimeout = function (fn,delay) {
        var id = counter++;
        ids[id] = newJavaAdapter(java.util.TimerTask,{run: fn});
        timer.schedule(ids[id],delay);
        return id;
    }

    clearTimeout = function (id) {
        ids[id].cancel();
        timer.purge();
        delete ids[id];
    }

    setInterval = function (fn,delay) {
        var id = counter++; 
        ids[id] = newJavaAdapter(java.util.TimerTask,{run: fn});
        timer.schedule(ids[id],delay,delay);
        return id;
    }

    clearInterval = clearTimeout;

})()

Solution 2:

Have a look at the Multithreaded Script Execution example on the Rhino Examples page. Basically, JavaScript does not support threading directly, but you may be able to use a Java thread to achieve what you are looking for.

Solution 3:

Another version using ScheduledThreadPoolExecutor, compatible with Rhino 1.7R4 and proposed by @Nikita-Beloglazov:

varsetTimeout, clearTimeout, setInterval, clearInterval;

(function () {
    var executor = new java.util.concurrent.Executors.newScheduledThreadPool(1);
    var counter = 1;
    var ids = {};

    setTimeout = function (fn,delay) {
        var id = counter++;
        var runnable = newJavaAdapter(java.lang.Runnable, {run: fn});
        ids[id] = executor.schedule(runnable, delay, 
            java.util.concurrent.TimeUnit.MILLISECONDS);
        return id;
    }

    clearTimeout = function (id) {
        ids[id].cancel(false);
        executor.purge();
        delete ids[id];
    }

    setInterval = function (fn,delay) {
        var id = counter++;
        var runnable = newJavaAdapter(java.lang.Runnable, {run: fn});
        ids[id] = executor.scheduleAtFixedRate(runnable, delay, delay, 
            java.util.concurrent.TimeUnit.MILLISECONDS);
        return id;
    }

    clearInterval = clearTimeout;

})()

Reference: https://gist.github.com/nbeloglazov/9633318

Post a Comment for "How To Run A Javascript Function Asynchronously, Without Using Settimeout?"