Something you have to remember is that JavaScript is inherently single threaded -- this means that when you set up an event, or an event is fired (by external situations or by the program itself) it cannot run right then and there. It is added to the execution queue and will not run until the current code snippet has finished running.
It's like a settimeout of zero... no matter how long or how much code you put after that settimeout, it will NEVER run until the control is handed back to the browser from the currently running JavaScript.
<script>
setTimeout(function() { alert('wtf'); }, 0);
for (var t = 1; t < 1000; t++) console.log('waiting');
</script>
If you saved that snippet as your ENTIRE HTML file, No matter how many times you set that to loop for the alert will not fire until AFTER the loop is finished and the markup finishes being parsed and all other scripting has ended.
Whereas you call a function, it runs right then and there.
Events can fire at any time in any order by any trigger, with a function "It's now or never"
Marco Alka
Software Engineer, Technical Consultant & Mentor
The main advantage of messages and events is, that the emitter does not (need to) know what is called. For example, if you have a button in your HTML and someone clicks it, your browser has no way to call a function in your JS (because that's your code), so it sends an
onclickevent. You can then write some JS, which listens for that event and acts upon it.<!-- -- The browser knows that there is a button. -- However it does not know what to call when it is clicked. -- So it just sends out an event, to whoever it may concern. -- That might be noone, or a thousand handler functions. -- Your browser, though, does not care and just does its thing. --> <button id="sample-btn">Hello!</button>const buttonClickHandler = _ => console.log('Hello'); // In JS, you can add a listener, // which is called whenever the event is fired. document .querySelector('#sample-btn') .addEventListener('click', buttonClickHandler) ; // You can even remove the listener // once you are not interested in the event anymore! document .querySelector('#sample-btn') .removeEventListener('click', buttonClickHandler) ;