为什么异步 XMLHttpRequest 比同步请求更受欢迎? [英] Why are asynchronous XMLHttpRequests preferred over synchronous requests?

查看:31
本文介绍了为什么异步 XMLHttpRequest 比同步请求更受欢迎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步和同步的区别是什么?区别对请求有什么影响?

What's the difference between asynchronous and synchronous and how does the difference effect the request?

推荐答案

来自关于 同步和异步请求:

XMLHttpRequest 支持同步和异步通信.但是,出于性能原因,一般而言,异步请求应优先于同步请求.

XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.

简而言之,同步请求会阻塞代码的执行,并可能泄漏内存和事件.这可能会导致严重的问题.使用同步请求的唯一可行原因是更容易在 Web Workers 内促进下载.

In short, synchronous requests block the execution of code and can leak memory and events. This can cause serious issues. The only viable reason to use synchronous requests is to more easily facilitate downloads within Web Workers.

异步请求是 XMLHttpRequest 存在的主要原因.XMLHttpRequest 支持 AJAX,其思想是让您的 JavaScript 代码运行并且您的用户可以对您的页面执行任何操作,而您的 JavaScript 在后台与服务器通信.例如,Gmail 以这种方式加载您的电子邮件.

Async requests are the main reason why XMLHttpRequest exists. XMLHttpRequest underpins AJAX, the idea of which is to let your JavaScript code run and your user do whatever with your page whilst your JavaScript communicates with the server in the background. Gmail loads your emails this way, for instance.

同步请求会在传输完成时阻止您的脚本运行.简而言之,当异步请求可用时,没有理由这样做.如果您的 Gmail 一直冻结会很烦人,您不觉得吗?您很少(如果有的话)想要使用同步请求.

Synchronous requests block your script from running whilst the transfer completes. Simply put, there's no reason to do this when async requests are available. It would be pretty annoying if your Gmail were freezing up all the time, don't you think? You rarely, if ever, want to use a synchronous request.

有些情况你必须使用同步请求,但在这些情况之外,您可能完全没有理由发出同步请求,而完全有理由使用异步请求.

There are circumstances you must use a synchronous request, but outside of those circumstances you'll likely have absolutely no reason to make a synchronous request, and every reason to use an asynchronous one.

这篇关于为什么异步 XMLHttpRequest 比同步请求更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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