how to run a javascript function asynchronously, without using setTimeout?

dark_ruby picture dark_ruby · Feb 14, 2010 · Viewed 9.1k times · Source

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

Answer

Weston C picture Weston C · Apr 24, 2011

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

var setTimeout,
    clearTimeout,
    setInterval,
    clearInterval;

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

    setTimeout = function (fn,delay) {
        var id = counter++;
        ids[id] = new JavaAdapter(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] = new JavaAdapter(java.util.TimerTask,{run: fn});
        timer.schedule(ids[id],delay,delay);
        return id;
    }

    clearInterval = clearTimeout;

})()