JavaScript函数是异步的吗? [英] Are JavaScript functions asynchronous?

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

问题描述

考虑执行以下功能,

function loadPage()
{
    takeInput();
    processInput();
    outputInput();
}

以什么顺序执行它们(我它紧随堆栈,所以选项2将是答案)?

In what order would they be executed(I have read that it follows stack so option 2 will be the answer)?

选项1

  1. takeInput();
  2. processInput();
  3. outputInput();

选项#2

  1. outputInput();
  2. processInput();
  3. takeInput();

推荐答案

JavaScript函数是异步的.一些非常有限的函数集具有异步API:

JavaScript functions are not asynchronous. Some very limited set of functions have an asynchronous API:

addEventListenersetTimeoutsetInterval.这是仅有的三个(我认为这很令人惊讶).

addEventListener, setTimeout, setInterval. These are the only 3 (which I thought was very surprising).

它们允许您传递可能最终被调用的回调.例如计时器到期,用户单击某物或AJAX请求完成时.

They allow you to pass in a callback that may get called eventually. Such as when a timer expires, or when a user clicks on something, or when an AJAX request completes.

JavaScript具有事件循环.事件循环处理每个事件的发生.如果您单击按钮3次,然后计时器到期,这也将是处理事件的顺序.一切都定义和确定得很好.

JavaScript has an event loop. The event loop processes each event as it comes in. If you click a button 3 times and then a timer expires that will also be the order the events are handled. It is all very well defined and determined.

此外,JavaScript没有线程,它会完全运行一个事件,直到开始下一个事件之前无事可做(返回)为止.因此,事件永远不会以任何方式发生干扰.这使您可以对数据状态做出非常严格的假设.

Furthermore, JavaScript doesn't have threads, it runs one event completely till there is nothing left to do (you return) before starting the next event. So events will never interfere in any way. This allows you to make very strong assumptions about the state of your data.

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

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