1

I have an extension for Google Chrome where I attempt to trigger a click of a button on the page, then wait 2 seconds, then print a message. When the button is clicked, it turns blue to show that it has been selected.

let element = document.getElementsByClassName("Button Button--alt Button--custom move-action-btn roster-action-btn").item(0);
element.addEventListener(("click"), function(){
    console.log("clicked")
})
element.click()
sleep(2000)
console.log("done")

I would expect this to click the button (and I see it turn blue), log "clicked", wait 2 seconds, then log "done". However, it logs "clicked", waits 2 seconds, logs "done", then the button turns blue and appears to have been clicked, seemingly immidiately after it logs "done".

If Javascript .click() is synchronous, why does the button appear to be clicked after the function is ran, and why is the actual result of the click after the event listener?

The sleep function for those wondering:

function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}
John Does
  • 19
  • 2

0 Answers0