为什么Alert函数的执行速度比javascript中的任何其他函数都要快? [英] Why does Alert function execute faster than any other functions in javascript?

查看:132
本文介绍了为什么Alert函数的执行速度比javascript中的任何其他函数都要快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,代码执行是从上到下开始的。在以下情况下,为什么 alert()函数的执行速度比之前找到的代码行还要快。

As far I as know, code execution starts from top to bottom. In the following cases, why does alert() function executes faster than line of codes found before it.

案例1 Alert() console.log()

console.log('Why was I executed last???')

alert('Alert 1')
alert('Alert 2')
alert('Alert...')

情况2: Alert() DOM 函数要快。

document.getElementById('btn').addEventListener('click', e => {
  e.target.previousElementSibling.style.color = 'red';
  alert('Alert is faster');
})

<div>Red Text</div>
<button id='btn'>Click me</button>

推荐答案

这不是更快,尽管我可以看到你是怎么到达那里的,而是它是同步

It's not that it's faster, though I can see how you got there, it's that it's synchronous.

警报确认提示是1990年代的文物,在现代网络编程中几乎没有地位¹。它们使主要的UI和JavaScript线程停顿下来,显示对话框,并等待用户执行某些操作。

alert, confirm, and prompt are relics from the 1990s with little to no place in modern web programming¹. They bring the main UI and JavaScript thread to a screeching halt, show the dialog box, and wait for the user to do something.

JavaScript不能做的其他事情去做。用于显示内容的其他操作会修改DOM,然后在下次浏览器重新绘制页面时异步地绘制这些更改。

Nothing else you can do from JavaScript can do that. The other things you do to display things modify the DOM, and those changes get drawn later, asynchronously, the next time the browser repaints the page.

在您的事件处理程序中,您已经更改了元素的颜色,但是浏览器还没有机会呈现该更改,因为 alert 具有

In your event handler, you've changed the color of the element, but the browser hasn't had a chance to render that change yet, because the alert has this anachronistic, synchronous stop-the-world behavior.

请注意,不同的浏览器对这些事情的处理方式不同。即使显示警报,某些浏览器也可能以红色显示该元素。其他人没有。在您的第一个示例中,有些可能很好地显示了控制台的输出。

Note that different browsers handle these things differently. Some browsers may well show the element in red even when the alert is showing. Others don't. Some may well show the console output in your first example; others don't.

通常,请避免提醒确认提示赞成使用现代替代品–由于这个原因,由于它们与 focus / blur 事件的奇特交互,因为它们无法设置样式。 ..

In general, avoid alert, confirm, and prompt in favor of using modern replacements — for this reason, because of the odd interactions they have with focus/blur events, because they cannot be styled, ...

这样做(避免警报确认提示)在ES2018中通过添加 async 函数变得更容易很多。并且使用转译器,即使您需要定位IE11等较旧的浏览器,也可以使用 async 函数。

Doing that (avoiding alert, confirm, and prompt) got a lot easier in ES2018 with the addition of async functions. And with a transpiler, you can use async functions even if you need to target older browsers like IE11.

¹并且现代浏览器正在逐渐减少对它们的支持,例如Chrome的 not 行为使警报标签不活动时停止代码。

¹ And modern browsers are chipping away at support for them, for instance Chrome's behavior of not making alert stop the code when the tab isn't active.

这篇关于为什么Alert函数的执行速度比javascript中的任何其他函数都要快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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