0

If I run

for (let i = 0; i < 1000; i++) {
  console.log(i)
}
window.alert('Hello World!');

then alert box pops up before for loop gets done.

But instead of using for loop, if I write simply console.log(1).. console.log(1000) statements and then put window.alert('Hello World'). It waits until all the console.log function gets executed.

console.log(1)
console.log(2)
.
.
.
console.log(1000)
console.log('Hello World');

Both ways of putting console.log statements do the same thing. But behaviour of alert box is different in each situation.

Why it happens so ? If alert is part of web API, shouldn't it get pushed inside the message queue and then pushed to the call stack only (by event loop) when stack becomes empty ? Why alert appears in middle of for loop in first case ?

user3760959
  • 457
  • 1
  • 6
  • 18
  • 1
    The `console` APIs have a degree of asynchronous behavior that varies from browser to browser. – Pointy Aug 28 '20 at 18:57
  • 1
    Does this answer your question? [Why does alert(); run before console.log();](https://stackoverflow.com/questions/47127173/why-does-alert-run-before-console-log) – Nicolae Aug 28 '20 at 18:59
  • 2
    in short: this has nothing to do with `alert`. Console functions get scheduled, so that they do not block the JS thread (unlike `alert`, which is a terrible function that can barely print anything and does block the entire JS thread). They don't execute immediately. – Mike 'Pomax' Kamermans Aug 28 '20 at 19:05
  • @ Mike 'Pomax' Kamermans : Okay. But isn't alert part of web API ? If that so, why it blocks the JS thread ? Thanks. – user3760959 Aug 29 '20 at 06:06

0 Answers0