为什么alert();在console.log()之前运行; [英] Why does alert(); run before console.log();

查看:326
本文介绍了为什么alert();在console.log()之前运行;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与其他人的不同



我使用的是ES6语法。我查看的其他问题使用ES5语法。



问题



为什么 alert(); console.log(); 之前运行?我可以这样做,以便 console.log(); alert();

我的代码

  console.log(你好!); 
alert(嗨!);


解决方案

  console。日志( 你好!); 
setTimeout(()=> alert(嗨!),0);

基本上:在技术上首先调用console.log() 但是,浏览器实际重新绘制自己或控制台更新也需要一些时间。在它可以自我更新之前,alert()已经触发,它说在我确认之前停止所有事情。所以发送到console.log的消息,但是视觉确认不及时。



在0秒内包装一些东西setTimeout是告诉JavaScript的一个老把戏嘿,完成所有运行和更新后立即打电话给我。






†你可以通过在警告对话框之前执行类似 console.log(new Date()。toString()); 之类的操作来验证这一点,然后在关闭警报之前等待几分钟。请注意,它会记录您第一次运行它的时间,不是现在的时间。


How My Question is Different From Others

I am using ES6 syntax. The other questions I looked at uses ES5 syntax.

The Question

Why does alert(); run before console.log();? And can I make it so that console.log(); is executed before alert();?

My Code

console.log("Hello!");
alert("Hi!");

解决方案

console.log("Hello!");
setTimeout(() => alert("Hi!"), 0);

Basically: console.log() is being called first, technically. However, the browser actually repainting itself or the console updating also takes a moment. Before it can update itself though, alert() has already triggered, which says "stop everything before I'm confirmed". So the message to console.log is sent, but the visual confirmation isn't in time.

Wrapping something in a 0 second setTimeout is an old trick of telling JavaScript "hey call me immediately after everything is finished running & updating."


† You can verify this by doing something like console.log(new Date().toString()); before the alert dialog, then waiting a few minutes before closing the alert. Notice it logs the time when you first ran it, not the time it is now.

这篇关于为什么alert();在console.log()之前运行;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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