什么时候JavaScript同步

什么时候JavaScript同步

本文介绍了什么时候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只是异步的,因为它可以例如,make,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调用上有一个选项可以使它们同步(使用<$ c) $ c> 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同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 13:44