Javascript:如何编写将异步执行的函数?

Ale*_*ack 4 javascript multithreading asynchronous web-worker

我有几行代码,我想在Javascript中异步运行,这样它不会减慢我的主算法.看到这个伪代码:

//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
Run Code Online (Sandbox Code Playgroud)

我在Stackoverflow中搜索了如何在Javascript中编写异步代码,但以下问题与我的不同:

我想我可以为此目的使用计时器.我想要的只是函数runInParallel()的主体,如果可能的话,它可以与我的主算法并行地高效运行代码.任何人?

Ioa*_*mas 5

Javascript没有同步/线程管理.如果您希望异步执行某些操作,可以setTimeout结合使用回调函数在函数完成时收到通知.

 var asyncHandle = setTimeout(function () { asyncCode(); callback(); }, 10);
Run Code Online (Sandbox Code Playgroud)

所述asyncHandle可用于取消之前被调用的函数的超时时间.

  • 我不同意.为什么要限制对支持HTML 5的客户端的支持以获得如此微不足道的事情? (2认同)