Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!