I have a few lines of code that I want to run asynchronously in Javascript so that it doesn’t slow down my main algorithm. See this pseudo code:
//main algorithm with critical code that should run as soon as possible
...
...
runInParallel(function(){
//time consuming unimportant code to shows some progress feedback to user
...
}
//the rest of the time critical algorithm
...
...
runInParallel(function(){
//time consuming unimportant code to shows some progress feedback to user
...
}
//and so on and so forth
I searched Stackoverflow for how to write asynchronous code in Javascript but the following questions are not similar to mine:
- how to run a javascript function asynchronously, without using setTimeout?: it’s about server side
- Loading javascript asynchronously – How to do callbacks?: it’s about loading source code
I guess I can use timers for this purpose. All I want is the body of the function runInParallel() that runs a code efficiently in parallel with my main algorithm with lower priority if possible. Anyone?
Javascript has no synchronization / thread management. If you wish to execute something asynchronously, you can use
setTimeoutcombined with a callback to be notified when the function ‘s finished.The
asyncHandlecan be used to cancel the timeout prior to the function being called.