JavaScript的:如何编写将异步执行的功能? [英] Javascript: How to write a function that will be executed asynchronously?
问题描述
我有code的几行,我想在Javascript异步运行,以便它不是我的主要算法放缓。看到这个伪code:
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
我搜索#1怎么写异步code在Javascript但下面的问题是不是与我的类似:
I searched Stackoverflow for how to write asynchronous code in Javascript but the following questions are not similar to mine:
- how异步运行JavaScript函数,而无需使用setTimeout的:它是关于服务器端
- Loading异步JavaScript的 - 怎么做回调:这是关于加载源$ C $ C
- 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
我想我可以使用定时器用于这一目的。我要的是能够有效运行code并行与我的主要算法具有较低优先级如果有可能的功能runInParallel()的主体。有人吗?
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有没有同步/线程管理。如果你想异步执行的东西,你可以使用的setTimeout
用相结合的回调时得到通知功能的完成。
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);
的 asyncHandle
可用于取消超时被调用的函数之前。
The asyncHandle
can be used to cancel the timeout prior to the function being called.
这篇关于JavaScript的:如何编写将异步执行的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!