9

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

2 Answers2

15
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.

SamVK
  • 3,077
  • 1
  • 14
  • 19
  • How can I make `alert();` come after 5 seconds? – SantaticHacker Nov 05 '17 at 22:27
  • 1
    @SantaticHacker If you want that, then you'd just use a `setTimeout` but, well, for it's intended use - not as this hacky side-effect thing we're doing above. So change it to `setTimeout(() => alert("Hi!"), 5000);` (The second argument to setTimeout is the number of milliseconds to wait before executing.) – SamVK Nov 05 '17 at 22:30
  • Oh, I thought that number was in seconds. Thanks anyway. – SantaticHacker Nov 05 '17 at 22:32
1

Check test below, which will return from function on 999 cycle of for loop before window.alert function fires. In my case I did not see window.alert. This is because actually alert runs after loop of console.log's functions.

// 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);
tarkh
  • 2,424
  • 1
  • 9
  • 12