When is JavaScript synchronous?(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.
这篇关于JavaScript 何时同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 何时同步?
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01