Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!");
like image 241
SantaticHacker Avatar asked Nov 05 '17 22:11

SantaticHacker


People also ask

Is alert and console log same?

alert() stops all interaction with the browser until the message is dismissed while console. log() just prints the message to the console.

What is the purpose of the alert () method?

The alert() method displays an alert box with a message and an OK button. The alert() method is used when you want information to come through to the user.

What happens when JavaScript runs the alert () function?

One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen.

What are command alert () and console log () use for what is the difference between these commands?

alert() converts the object passed to it into a string using the object's toString() method. Unlike alert(), console. log() is not only limited to displaying a simple string but also allow you to interact with the object passed to it. For example letting you inspect its properties.


1 Answers

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.

like image 142
SamVK Avatar answered Oct 21 '22 13:10

SamVK