Order of execution - JavaScript

Hello.

In the following example, why is the second line(alert) happening before the first one?

times.style.display = "block";
alert();

What can do to make the script run according to the order I have written down?


Best regards
Neo

With many browsers, the visual update doesn’t occur because JavaScript is still in the middle of executing code.

Using alerts is discouraged because it’s a blocking operation, but you can use setTimeout to delay the alert until the screen has updated itself.

1 Like

Hello Paul. Thanks for the reply.

I’ll try that.

@Paul_Wilkins’s answer is right.

If you want to really understand the order of execution and how asynchronous code is handled, watch this video:

There’s a lot more to it than what’s covered there, but it’s a good start. Fully understanding it can be complicated.

It’s also a measure of efficiency. Consider the following code:

times.style.display = "block";
times.style.display = "hidden";
times.style.display = "inline";
times.style.display = "hidden";
times.style.display = "block";
times.style.display = "inline";

Now, the browser could render every one of those changes in turn, waiting for the previous render to complete.
Or, it could wait a microsecond or two, read the final state, and only render the element’s state once, with little to no appreciable difference in the result.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.