jQuery setTimeout 是使用 javascript 执行异步函数的好方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19626680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is setTimeout a good solution to do async functions with javascript?
提问by viniciuswebdev
Searching in the web about async functions, I found many articles using setTimeout to do this work:
在网上搜索有关异步函数的信息,我发现很多文章使用 setTimeout 来完成这项工作:
window.setTimeout(function() {
console.log("second");
}, 0);
console.log("first");
Output:
输出:
first
second
This works, but is a best practice?
这行得通,但这是最佳实践吗?
回答by tybro0103
setTimeout(function(){...}, 0)
simply queues the code to run once the current call stack is finished executing. This can be useful for some things.
setTimeout(function(){...}, 0)
一旦当前调用堆栈完成执行,只需将代码排队即可运行。这对某些事情很有用。
So yes, it's asynchronous in that it breaks the synchronous flow, but it's not actually going to execute concurrently/on a separate thread. If your goal is background processing, have a look at webworkers. There's also a way to use iframes for background processing.
所以是的,它是异步的,因为它打破了同步流程,但它实际上不会并发/在单独的线程上执行。如果您的目标是后台处理,请查看webworkers。还有一种使用 iframe 进行后台处理的方法。
Update:
更新:
To further clarify, there's a difference between concurrency/backgrounding and asynchronous-ness. When code is asynchronous that simply means it isn't executed sequentially. Consider:
为了进一步澄清,并发/背景和异步之间存在差异。当代码是异步的时,仅仅意味着它不是按顺序执行的。考虑:
var foo='poo';
setTimeout(function() {
foo='bar'
}, 100);
console.log(foo);
The value 'poo' will be alerted because the code was not executed sequentially. The 'bar' value was assigned asynchronously. If you need to alert the value of foo
when that asynchronous assignment happens, use callbacks:
由于代码未按顺序执行,因此将警告值“poo”。'bar' 值是异步分配的。如果您需要提醒foo
异步赋值发生的时间,请使用回调:
/* contrived example alert */
var foo = 'poo';
function setFoo(callback) {
setTimeout(function() {
foo = 'bar';
callback();
}, 100);
};
setFoo(function() {
console.log(foo);
});
So yes, there's some asynchronous-ness happening above, but it's all happening in one thread so there are no performance benefits.
所以是的,上面发生了一些异步性,但这一切都发生在一个线程中,因此没有性能优势。
When an operation takes a long time, it is best to do it in the background. In most languages this is done by executing the operation on a new thread or process. In (browser) javascript, we don't have the ability to create new threads, but can use webworkers or iframes. Since this code running in the background breaks the sequential flow of things it is asynchronous.
当一个操作需要很长时间时,最好在后台进行。在大多数语言中,这是通过在新线程或进程上执行操作来完成的。在(浏览器)javascript 中,我们无法创建新线程,但可以使用 webworkers 或 iframe。由于这段在后台运行的代码打破了事物的顺序流,因此它是异步的。
TLDR: All backgrounded/concurrent code happens asynchronously, but not all asynchronous code is happening concurrently.
TLDR:所有后台/并发代码都是异步发生的,但并非所有异步代码都是并发发生的。
See Also: Understanding Asynchronous Code in Layman's terms
另请参阅:用外行的术语理解异步代码
回答by Vaisakh Rajagopal
var foo = 'poo';
setTimeout(function() {foo = 'bar'}, 100);
alert(foo);
A small correction to @tybro0103 's answer, during the execution of 'alert(foo)' the value 'poo' will not change because the code was not executed sequentially. The 'bar' value was assigned asynchronously and it will execute only after 100 millisecond, by that time alert will be executed.
对@tybro0103 的回答的一个小更正,在执行 'alert(foo)' 期间,值 'poo' 不会改变,因为代码不是按顺序执行的。'bar' 值是异步分配的,它只会在 100 毫秒后执行,届时将执行警报。
The value of fooremains unaltered, during the execution of line alert(foo). And will change later on time. Check @vishal-lia comment.
在执行行 alert(foo) 期间,foo的值保持不变。并且会及时更改。检查@vishal-lia 评论。
回答by Shashank Gupta
By default, JavaScript is asynchronous whenever it encounters an async function, it queued that function for later. But if you want a pause js for you can do it use promises Case 1: output hello(will not wait for setTimeout) https://jsfiddle.net/shashankgpt270/h0vr53qy/
默认情况下,JavaScript 在遇到异步函数时是异步的,它会将该函数排入队列以备后用。但是,如果您想要暂停 js,则可以使用 promises 案例 1:输出 hello(不会等待 setTimeout) https://jsfiddle.net/shashankgpt270/h0vr53qy/
//async
function myFunction() {
let result1='hello'
//promise =new Promise((resolve,reject)=>{
setTimeout(function(){
resolve("done");
result1="done1";
}, 3000);
//});
//result = await promise
alert(result1);
}
myFunction();
case 2: output done1(will wait for setTimeout) https://jsfiddle.net/shashankgpt270/1o79fudt/
情况 2:输出 done1(将等待 setTimeout) https://jsfiddle.net/shashankgpt270/1o79fudt/
async function myFunction() {
let result1='hello'
promise =new Promise((resolve,reject)=>{
setTimeout(function(){
resolve("done");
result1="done1";
}, 3000);
});
result = await promise
alert(result1);
}
myFunction();