JavaScript 何时同步?

2022-01-30 00:00:00 jquery javascript

我一直认为 JavaScript 总是异步的.但是,我了解到有些情况并非如此(即 DOM 操作).是否有关于何时同步和何时异步的良好参考?jQuery 对此有影响吗?

I have been under the impression for that JavaScript was always asynchronous. However, I have learned that there are situations where it is not (ie DOM manipulations). Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous? Does jQuery affect this at all?

推荐答案

JavaScript 始终是同步和单线程的. 如果您在页面上执行 JavaScript 代码块,则没有其他 JavaScript当前将在该页面上执行.

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript 只是异步的,因为它可以进行例如 Ajax 调用.Ajax 调用将停止执行,其他代码将能够执行,直到调用返回(成功或失败),此时回调将同步运行.此时不会运行其他代码.它不会中断当前正在运行的任何其他代码.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

JavaScript 计时器使用相同类型的回调进行操作.

JavaScript timers operate with this same kind of callback.

将 JavaScript 描述为异步可能会产生误导.更准确的说法是 JavaScript 是同步的单线程的,有各种回调机制.

Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery 有一个关于 Ajax 调用的选项以使它们同步(使用 async: false 选项).初学者可能会不正确地使用它,因为它允许使用可能更习惯的更传统的编程模型.有问题的原因是此选项将阻止页面上的所有 JavaScript,直到它完成,包括所有事件处理程序和计时器.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

相关文章