setTimeout是用javascript做异步函数的好方法吗? [英] Is setTimeout a good solution to do async functions with javascript?

查看:128
本文介绍了setTimeout是用javascript做异步函数的好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网上搜索异步函数,我发现很多文章使用setTimeout来完成这项工作:

Searching in the web about async functions, I found many articles using setTimeout to do this work:

window.setTimeout(function() {
   console.log("second");
}, 0);
console.log("first");

输出:

first
second

这有效,但是最佳做法?

This works, but is a best practice?

推荐答案

setTimeout(function(){...},0)只需将代码排队,即可在当前调用堆栈执行完毕后运行。这可以是对某些内容有用

setTimeout(function(){...}, 0) simply queues the code to run once the current call stack is finished executing. This can be useful for some things.

所以是的,它是异步的,因为它打破了同步流,但实际上并不是在一个单独的线程上同时执行。如果您的目标是后台处理,请查看 webworkers 。还有一种方法可以使用iframe进行后台处理。

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.

更新

为了进一步说明,并发/后台和异步之间存在差异。当代码是异步的时,这意味着它不是按顺序执行的。考虑:

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);
alert(foo);

值'poo'将被警告,因为代码没有按顺序执行。 'bar'值是异步分配的。如果您需要在异步分配发生时提醒 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:

/* contrived example alert */
var foo = 'poo';
function setFoo(callback) {
  setTimeout(function(){
    foo = 'bar';
    callback();
  }, 100);
};
setFoo(function() {
  alert(foo);
});

所以是的,上面发生了一些异步现象,但这一切都发生在一个线程中,所以有没有性能优势。

So yes, there's some asynchronous-ness happening above, but it's all happening in one thread so there are no performance benefits.

当操作需要很长时间时,最好在后台执行。在大多数语言中,这是通过在新线程或进程上执行操作来完成的。在(浏览器)javascript中,我们无法创建新线程,但可以使用webworkers或iframe。由于此代码在后台运行会破坏事物的顺序流,因此它是异步的。

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.

TLDR :所有后台/并发代码都是异步发生的,但并非所有异步代码都同时发生。

TLDR: All backgrounded/concurrent code happens asynchronously, but not all asynchronous code is happening concurrently.

另请参阅了解异步代码Layman的条款

这篇关于setTimeout是用javascript做异步函数的好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆