[removed] How to write a function that will be exe

2019-05-11 22:41发布

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?

2条回答
Animai°情兽
2楼-- · 2019-05-11 23:28

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.

查看更多
甜甜的少女心
3楼-- · 2019-05-11 23:40

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.

查看更多
登录 后发表回答