如何使非拦截JavaScript code?

问题描述:

我怎样才能做一个简单的,无阻塞的JavaScript函数调用?例如:

How can I make a simple, non-block Javascript function call? For example:

  //begin the program
  console.log('begin');
  nonBlockingIncrement(10000000);
  console.log('do more stuff'); 

  //define the slow function; this would normally be a server call
  function nonBlockingIncrement(n){
    var i=0;
    while(i<n){
      i++;
    }
    console.log('0 incremented to '+i);
  }

输出

"beginPage" 
"0 incremented to 10000000"
"do more stuff"

我如何能形成这种简单的循环异步执行和输出通过一个回调函数的结果?我们的想法是不会阻止做更多的东西:

How can I form this simple loop to execute asynchronously and output the results via a callback function? The idea is to not block "do more stuff":

"beginPage" 
"do more stuff"
"0 incremented to 10000000"

我试过以下的回调和延续的教程,但他们似乎都依赖于外部库或功能。他们没有回答一个真空的问题!?如何来编写JavaScript code是非阻塞

I've tried following tutorials on callbacks and continuations, but they all seem to rely on external libraries or functions. None of them answer the question in a vacuum: how does one write Javascript code to be non-blocking!?

我已搜查非常困难的,要求在此之前答案;请不要以为我没有看。一切我发现的是特定的Node.js([1], [2], [3], [4], [5])或以其他方式具体到其他功能或库([6], [7], [8], [9], [10], [11]),值得注意的是jQuery和的setTimeout()。请帮我写使用的的JavaScript 的非阻塞code,而不是使用Javascript编写的工具,如jQuery和节点标记为重复之前,请重读的问题。

I have searched very hard for this answer before asking; please don't assume I didn't look. Everything I found is Node.js specific ([1], [2], [3], [4], [5]) or otherwise specific to other functions or libraries ([6], [7], [8], [9], [10], [11]), notably JQuery and setTimeout(). Please help me write non-blocking code using Javascript, not Javascript-written tools like JQuery and Node. Kindly reread the question before marking it as duplicate.

的setTimeout与回调是要走的路。虽然,了解你的功能范围是不一样的在C#或其他多线程环境。

SetTimeout with callbacks is the way to go. Though, understand your function scopes are not the same as in C# or another multi-threaded environment.

JavaScript没有等待你的函数的回调完成。

Javascript does not wait for your function's callback to finish.

如果你说:

function doThisThing(theseArgs) {
    setTimeout(function (theseArgs) { doThatOtherThing(theseArgs); }, 1000);
    alert('hello world');
}

您的警报会解雇你会传递函数之前。

Your alert will fire before the function you passed will.

区别在于警报受阻线程,但回调没有。

The difference being that alert blocked the thread, but your callback did not.