0

I have a problem understanding the Javascript event loop and code execution.

For example, I have a very basic jQuery function like:

$(document).ready(function()
{
$('#button').on('click', function() {
alert("This is a test");
});

Can somebody please explain to me, when the jQuery function gets called?
What happens if the page is loaded, is the .ready() function put on the message queue and gets passed to the event loop when the callback for the function is fired? (In this case, the callback would be the finish loaded page?)

4
  • 2
    See developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop: "In web browsers, messages are added any time an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message--likewise with any other event." The ready callback is just another event handler. Commented Aug 16, 2014 at 15:11
  • What message queue? the callback function as you said is a function. Why'd you think it's "loaded page"?? Commented Aug 16, 2014 at 15:12
  • @TJ: See the link I posted. Commented Aug 16, 2014 at 15:15
  • Awesome video explaining the event the stack, the event loop etc youtube.com/watch?v=8aGhZQkoFbQ Commented Nov 8, 2016 at 15:57

1 Answer 1

2

The .ready() function gets called when DOM tree has been constructed from your HTML and that's why it is called DOM ready event. After this, the anonymous function above which has the alert gets bound to click event of the element with the ID button . This means that whenever this target is clicked (which has ID button) this function will be called, and hence your alert will show. I hope that helps !

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, but i think thats a little bit to generic. I want to know, how the eventloop works in this case. How does call stack, message queue and event loop work together in this case?
it is my understanding, that every function in js, which contains a callback, is first put on a Call Stack, and then, when their callback is fired, the function gets executed. Meanwhile the functions eventhandler is stored in a message queue, waiting for its event to be triggered. The event loop loops through the message queue, executing all triggered events waiting in the queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.