Search code examples
javascriptdom-eventssettimeout

Understanding setTimeout


I am playing around with setTimeout in Javascript. I am confused about how it works. I have the following code:

<input type="button" value='click'>

<script>
var input = document.getElementsByTagName('input')[0]

input.onclick = function() {
  setTimeout(function() { 
    input.value +=' input'  
  }, 0)
}

document.body.onclick = function() {
  input.value += ' body'
}
</script>

When we click the function, it appends the text body input to the button element. I understand this is happening because first the parent (body) event is triggered and at the next timer tick, the child (input) event is executed since it was pushed later in the event queue.

I now tried the following code:

var input = document.getElementsByTagName('input')[0]

document.body.onclick = function() {
  setTimeout(function() { 
    input.value +=' body'  
  }, 0)
}

input.onclick = function() {
  setTimeout(function() { 
    input.value +=' input'  
  }, 0)
}

This appends the text input body to the button element. How is it determining the order of execution here when both the timeouts are set to 0? In what order are they push to the event queue in this case?


Solution

  • The click is first triggered on the innermost element and then bubbled up.

    Therefore in your first example the click on input is triggered first but because of setTimeout it is not executed immediately instead it is added to the queue and thus event on body is triggered and executed.

    Now second scenario is explanatory, input is triggered first and it adds execution to the queue because of setTimeout but then when event on document is triggered it does the same and now the queue is executed therefore input is executed first and then document event,

    It is because JavaScript is single threaded therefore once setTimeout is triggered it pushes the function to the queue and waits for timeout and turn to execute it.

    Refrence for further Read W3.org Link