I play with setTimeout in Javascript. I am confused about how this 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 on this function, it adds a text element to the button element. I understand that this happens because the parent (body) event is triggered first and the next (child) input event is executed on the next tick of the timer, since it was transferred later to the event queue.
Now I 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 adds a text input body to the button element. How to determine the execution order here when both timeouts are set to 0? In what order do they click on the event queue in this case? Thank you
source
share