4

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:

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?

Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104

2 Answers2

5

Javascript has no synchronization / thread management. If you wish to execute something asynchronously, you can use setTimeout combined with a callback to be notified when the function 's finished.

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

The asyncHandle can be used to cancel the timeout prior to the function being called.

Ioannis Karadimas
  • 7,746
  • 3
  • 35
  • 45
  • these methods are quite obsolete, as from the introduction of web workers (see my post). – Eliran Malka Mar 08 '12 at 09:02
  • 2
    I don't agree. Why should you limit your support to HTML 5 enabled clients for such a trivial thing? – Ioannis Karadimas Mar 08 '12 at 09:05
  • one can argue about the adoption of web standards as means of enforcing acceptance by the browser vendors, but this is a whole other issue.. – Eliran Malka Mar 08 '12 at 09:15
  • I agree that something 's got to give, but most of the web is not HTML 5, so in the end, I guess you 'll be hurting your app by limiting its audience, rather than enforcing some standard. – Ioannis Karadimas Mar 08 '12 at 09:21
  • We have strict control over the runtime environment and we have HTML5 there. But I think Web Workers are too big for the problem that we have at the moment. For now I think this setTimeout() will do the job. However I agree that Web Workers may be the ultimate answer if our problem expands. – AlexStack Mar 08 '12 at 09:37
2

If you're targeting HTML5 supporting browsers, go with HTML5 Web Workers.

You can also try this interesting, but quite old JavaScript compiler that allows a language extension for this purpose.

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100