Javascript: how to write a function that will execute asynchronously?

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've searched Stackoverflow for writing asynchronous code in Javascript, but the following questions are not like mine:

I guess I can use timers for this purpose. All I want is the body of the runInParallel () function, which efficiently executes the code in parallel with my main algorithm at a lower priority, if possible. Anyone?

+3


source to share


2 answers


Javascript has no synchronization / flow control. If you want to execute something asynchronously, you can use it setTimeout

in conjunction with a callback to be notified when the function has completed.

 var asyncHandle = setTimeout(function () { asyncCode(); callback(); }, 10);

      



asyncHandle

can be used to cancel a timeout before calling a function.

+5


source


If you are targeting HTML5 browsers, go for HTML5 web workers .



You can also try this interesting but rather old JavaScript compiler that allows you to use a language extension for this purpose.

+2


source







All Articles