如何制作非阻塞的javascript代码? [英] How to make non-blocking 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 代码!?
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 编写非阻塞代码,而不是使用 Javascript 编写的工具,例如 JQuery 和 Node.请在将其标记为重复之前重读该问题.
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.
这篇关于如何制作非阻塞的javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!