its a server side Javascript (rhino engine), so setTimeout is not available. how to run a function asynchronously?
The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.
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.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.
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.
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;
})()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With