JS Questions: What’s the Event Loop?

This is the eleventh in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What’s the Event Loop?

Like any programming language, JavaScript has a specific process for handling function calls in a program, and more specifically, deciding when each function will run. Unlike other languages, JavaScript can be run in a browser, meaning that users may be interacting with the program by clicking a mouse or scrolling, for instance, simultaneous to other processes that are already running. The event loop helps create a fluid experience for users, by dictating a flow that allows for relatively long running processes to occur alongside client-side interactions.

Without features built into Node and browsers, JavaScript would only be able to handle one event at a time. Each function call would be added to a stack and one-by-one, popped off the top and run. It’s easy to imagine how this could become problematic in a web app. If a notice telling a user she had successfully updated her account were rendered to a webpage for three seconds using setTimeout, the user would not be able to interact with the page until the setTimeout had completed.

Some events do happen synchronously in JS. Loops will run in the call stack and prevent a webpage from re-rendering until they have completed.

However, due to the event loop built into browsers, processes such as AJAX requests and timeouts can run in the background, with their callback functions placed in a queue that are added to the call stack only when the entire stack has cleared. The below code snippet illustrates this.

If you paste this in your console, you’ll see 1 logged, then 2 returned, then 3 logged. Here’s what happens:

  1. The eventLoop function gets added to the call stack.
  2. The setTimeout timer begins and the callback function is added to the queue after 0 milliseconds.
  3. The number 1 is immediately logged.
  4. The eventLoop function returns 2 and the call stack is cleared.
  5. The setTimeout callback runs, logging 3.

Note that the call stack runs functions in ‘first in last out’ order (meaning that the first function added to a stack is the last to run). That’s why, in the code below, the strings are already concatenated when logged:

First, the greet function is added to the call stack. Then, the concat function is added to the call stack. Concat runs, the greeting is logged, and the greet function is cleared from the stack.

Meanwhile, the queue runs callback functions in ‘first in first out’ order. The first item added to the queue is the first to be added to the call stack. That means, if multiple AJAX requests are made, for instance, the first request to finish will be the first to have its callback function run.

In sum, the event loop in JavaScript refers to the synchronous and asynchronous flow dictated by the call stack and queue in browsers.

Resources

 

Advertisements

JS Questions: What is AJAX?

This is the third in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc. 

What is AJAX?

Websites used to be composed of static HTML pages. Each time a user interacted with the DOM, the entire page reloaded. AJAX, short for Asynchronous JavaScript and XML, is a bundle of technologies that allow web pages to be updated without completely reloading.

AJAX uses a functionality built into modern browsers called the XMLHttpRequest object, which has certain methods and properties that let web pages get data from a server.

The flow of an AJAX request and response cycle begins with an XMLHttpRequest object being created. Then the .open method is called on the object, which takes in three parameters:

  1. the type of request, GET or POST
  2. a URL to the requested data
  3. a boolean value of whether to send the request asynchronously. An asynchronous request means that other JavaScript functions can run while the response is being prepared and sent back from the server.

The .send method is then called on the XMLHttpRequest object, sending it to the server. The server processes the request and creates a response, returning data to the browser.

The data can be returned as XML (hence the XML part of the acronym), though it’s now more common to convert the data to JSON format, which simply allows developers to interact with data as if it’s a JavaScript object.

Using that JSON data, a portion of a web page’s HTML could be updated. For example, a JavaScript function could use HTML to create an unordered list, and append list items with text from the data.

Sources

JS Questions: What is the DOM?

This is the second in a series of posts I’m writing that aims to provide concise, understandable answers to Javascript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc. 

What is the DOM?

The DOM, or Document Object Model, is the structure of HTML elements that make up a web page. It’s often described as a tree, with the document object (or whole HTML document) being the root, and the head, body, div, etc nodes as branches.

The DOM is not a Javascript-specific interface, but Javascript can be used to access and modify DOM elements. With scripts, web pages can be made to react to user inputs, such as mouse clicks, for example, by–let’s say–removing or adding elements or modifying the css. We call these interactions client-side events.

Originally, short scripts were added to otherwise static HTML pages, but now Javascript can be used as the main source code for entire web sites.

Sources:

 

 

Getting Started in jQuery and the DOM

Last week, I started learning about jQuery and the DOM (Document Object Model). At first, I was really excited. Finally, I could dress up my JavaScript and bring it out in public! But within minutes of delving into the documentation, my eyes glazed over and I became filled with the feeling of hopelessness and dread that has become familiar in my code self-teaching experience. At that point, I closed my laptop and went to bed.

The next morning, though, I sat down at my computer with a new game plan. I’ve found that seeing examples of code (instead of reading about it in generalized terms) is usually the easiest way for me to make sense of new concepts. So–I actually don’t know why it took me so long to think of this–I went to YouTube.

This video (the first in a two-part series) from the DevTips channel was probably best out of all that I watched. It’s professionally made and has a really clever example of showing how an event listener (mouse movement) can be used to create this psychedelic color-changing window.

This DOM manipulation video is less flashy, but demonstrates some basic and very useful techniques. And this video, which is the start of a three part series, got me started in jQuery with some clear and straightforward examples.

For a few triumphant moments, I congratulated myself on conquering this one (admittedly relatively small) beast–I know what jQuery and the DOM are and the very basics of how to use them! Now, back to work…