简体   繁体   English

为什么 alert(); 在 console.log() 之前运行;

[英]Why does alert(); run before console.log();

How My Question is Different From Others我的问题与其他人有何不同

I am using ES6 syntax.我正在使用 ES6 语法。 The other questions I looked at uses ES5 syntax.我查看的其他问题使用 ES5 语法。

The Question问题

Why does alert();为什么alert(); run before console.log();console.log();之前运行console.log(); ? ? And can I make it so that console.log();我可以这样做, console.log(); is executed before alert();alert();之前执行alert(); ? ?

My Code我的代码

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

Basically: console.log() is being called first, technically.基本上:从技术上讲,console.log()首先被调用。 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".在它可以自我更新之前,alert() 已经触发,它说“在我确认之前停止一切”。 So the message to console.log is sent, but the visual confirmation isn't in time.所以发送到 console.log 的消息,但视觉确认不及时。

Wrapping something in a 0 second setTimeout is an old trick of telling JavaScript "hey call me immediately after everything is finished running & updating."在 0 秒内包装一些东西 setTimeout 是告诉 JavaScript “嘿,一切都完成运行和更新立即给我打电话”的老技巧。


† You can verify this by doing something like console.log(new Date().toString()); † 您可以通过执行诸如console.log(new Date().toString());类的操作来验证这一点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.请注意,它会记录您第一次运行时的时间,而不是现在的时间。

Check test below, which will return from function on 999 cycle of for loop before window.alert function fires.检查下面的测试,它将在 window.alert 函数触发之前在 for 循环的 999 次循环中从函数返回。 In my case I did not see window.alert.就我而言,我没有看到 window.alert。 This is because actually alert runs after loop of console.log's functions.这是因为警报实际上是在 console.log 的函数循环之后运行的。

 // Test function const test = (br) => { for (let i = 0; i < 1000; i++) { console.log(i); // If br true and cycle #999 - return before // loop end and window.alert exec if(br && i === 999) return; } window.alert('Hello World!'); }; // Test test(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM