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

后端 未结 3 367
无人及你
无人及你 2021-02-01 07:03

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

3条回答
  •  梦如初夏
    2021-02-01 07:14

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

    var setTimeout, 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 = new JavaAdapter(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 = new JavaAdapter(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

提交回复
热议问题