本文介绍了如何使非拦截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!?

推荐答案

的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.

这篇关于如何使非拦截JavaScript code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:27