问题
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?
回答1:
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.
回答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.
来源:https://stackoverflow.com/questions/9614953/javascript-how-to-write-a-function-that-will-be-executed-asynchronously