Home > other >  Do eventlisteners callback functions go into callback queue?
Do eventlisteners callback functions go into callback queue?

Time:10-31

I think depending on my understand that callback functions are placed in the callback queue and don't execute until callstack is empty, so in the following code, why does the callback function of the event listener is executed on button clicking while console.log(index) is running ? Should the background color changed after the execution of all functions console.log() existed in the callstack first?

<button>Click me</button>

<script>
    for (let index = 0; index < 100000; index  ) {
        console.log(index)   
    }

    document.querySelector('button').addEventListener('click',()=>{
        document.querySelector('body').style.backgroundColor = 'red'
    })
</script>

CodePudding user response:

Your code is all sync.

What will happen above is the thread will be blocked until for-loop ends.

then you’ll create a arrow function -that will capture global ctx- and be saved in memory

Code will pass the ref of this fn to addeventlistern which will push fn ref to list of callbacks to be called once event is emitted

to summarize yes button click will trigger bg.

In other words, until for-loop finish you didn’t event reach spot where you register callback so it won’t trigger (but a forloop of 10k will probably finish in less than ~10ms) after that you will register Cb and be good to go

CodePudding user response:

Yes, because the for loop is sync, so even if it's a loop of 100 thousand, they all start to run at the same time, so the rest of the code will also be executed and even before all the console log() are executed. An example to demonstrate that, I tried something similar once by putting a settimeout in a for loop to make a delay between each loop count like this

for (let i=0; i<31; i  ){
setTimeout(()=>console.log(i), 1000)
}
console.log('finished')

This should run console.log every 1 second, but the actual behavior is that the 30 loop counts start to run together and are executed in 1 second along with last console.log(). So, knowing that, I modified it to

for (let i=0; i<31; i  ){
setTimeout(()=>console.log(i), 
1000*(i 1))
}
console.log('finished')

Now after this modification, the loop will run every 1 second as we increased the timeout by 1 extra second for each loop count, which confirms that the loop counts all start at the same time, but the last console.log('finish') will run before the loop even starts logging as the loop is a sync code which won't be awaited to finish before the next line of code runs.

I hope this helps

  • Related