JavaScript 什么时候同步? [英] When is JavaScript synchronous?

查看:47
本文介绍了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 什么时候同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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