Search code examples
javascriptloopsevent-listener

Can't understand why this event listener should go into loop


I'm doing TOP curriculum and now I'm doing the Etch-A-Sketch project.

I created the grids with divs with a for loop. On my mouse hover, they should go black. I did it by putting the event listener into the loop but I can't understand why it should work like that.

for (count = 0; count < GRID_SIZE; count++) {
    let cell = document.createElement('div');
    cell.className = 'cell';
    gridHouse.appendChild(cell);
    cell.addEventListener('mouseover', () => cell.style.backgroundColor = 'black');
}

The loop starts, makes the squares, no problem here. What I can't understand is why event listener keeps working? Is there something listener does that prevents the loop ending?


Solution

  • The loop ends when the GRID_SIZE is reached. For each of those divs you're making you're also adding an eventListener that persists outside of the loop lifecycle. This is because of how the event loop works in javascript. Basically your code executes in a sequential order until you do something to it that's asynchronous. Web API events, XHR requests, and setting timers falls into this category.

    This guy explains it way better than I ever could. Well worth the watch. https://www.youtube.com/watch?v=8aGhZQkoFbQ