Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
Why event handler callback is getting executed immediately before entire call stack is executed?

Please help in explaining why the click event handler is executed before the script is finished executing.

console.log('Script started running')
document.body.addEventListener('click', () => {
  console.log('Click callback executed')
})
console.log('Before click')
document.body.click()
console.log('After click')

My expectation was

Script started running
Before click
After click
Click callback executed

But the output observed on running is

Script started running
Before click
Click callback executed
After click

Should the script not be executed fully(call stack made empty) before any event callback from the task queue is executed ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The HTMLElement.click() method simulates a mouse click on an element.

The handler has to be executed immediately before continuing the script.

If you were to remove this line and click manually, you would get your desired result.

console.log('Script started running')
document.getElementById('button').addEventListener('click', () => {
  console.log('Click callback executed')
})
console.log('Before click')
//document.body.click()
console.log('After click')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id='button'>Click me</button>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda