1

As my understanding about event loop, event loop will push the callbacks into the callstack, but for example, the following code, the sync code console.log(2) is running after the click event handler, why is that?

console.log(1)

document.body.addEventListener('click', () => {
  console.log(3)
})

document.body.click()

console.log(2)
ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • `document.body.click()` I don't believe goes via the event pump, you would need to dispatch the click event instead.. – Keith Dec 24 '21 at 08:29

1 Answers1

0

By doing :

console.log(1)

document.body.addEventListener('click', () => {
    console.log(3)
})

document.body.click()

console.log(2)

The result is :

1
3
2

But by doing :

console.log(1)

document.body.addEventListener('click', () => {
    setTimeout( () => {
        console.log(3)
    },200);
})

document.body.click()

console.log(2)

The result is :

1
2
3

So my conclusions are that the click event is well put in the stack, but that it unstacks instantly.

FS-GSW
  • 152
  • 9
  • Or maybe the `eventClick` is not put in the stack while the `setTimeout()` is. – FS-GSW Dec 24 '21 at 08:45
  • 1
    From my previous understanding, the click handler will be pushed into the task queue, and after the callstack is empty and the job queue is empty, the task in task queue will be running. I m confused about this. – ChenLee Dec 24 '21 at 08:46
  • THIS IS VERY CONFUSING... – FS-GSW Dec 24 '21 at 09:00
  • 1
    "*the click event is well put in the stack*" doesn't make sense. Only function calls are placed on the stack, not events. – Bergi Dec 24 '21 at 10:30