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

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

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 07:16

    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;
    
    })()
    

提交回复
热议问题