Why does alert(); run before console.log();

牧云@^-^@ 提交于 2019-12-23 09:17:18

问题


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!");

回答1:


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.



来源:https://stackoverflow.com/questions/47127173/why-does-alert-run-before-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!