Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 335
dark_ruby Avatar asked Feb 14 '10 16:02

dark_ruby


People also ask

What we can use instead of setTimeout in JavaScript?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.

How do I avoid setTimeout?

You can also prevent the setTimeout() method from executing the function by using the clearTimeout() method. If you have multiple setTimeout() methods, then you need to save the IDs returned by each method call and then call clearTimeout() method as many times as needed to clear them all.

Is JavaScript setTimeout asynchronous?

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

Can I use async function without await?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.


2 Answers

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;

})()
like image 176
Weston C Avatar answered Sep 20 '22 19:09

Weston C


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.

like image 21
Justin Ethier Avatar answered Sep 21 '22 19:09

Justin Ethier