Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

What are Web Workers in Javascript

This article is associated with the following course
Introduction to Web Workers

For websites and web applications, we rely on Javascript to handle logic, interacting with existing HTML and CSS on the page, and even use it to create and add DOM content on styles on our website. Javascript is essential in any developers toolset.

However, as time has gone on, web applications have become more complex. Applications that would’ve been previously built natively on desktop are now available on the web.

But many applications are now a lot more complex than they were back then. We have single page web applications now that handle multiple pages of content without ever having to refresh the page or go to a different url in the browser.

Even applications that are still one single page need plenty of complex Javascript for handling the business logic of their page.

As we continue to add more Javascript to our pages, our site needs to handle our Javascript and this could harm the user experience and the performance of a page.

Javascript by default runs on the main thread

Javascript that we run on the page by default runs on the main thread. Not just in web applications but also in other applications any code relating to the UI interface is run on the main thread. Why is that important? Because if the main thread is blocked, the user won’t be able to interact with the page

But wait, isn’t Javascript asynchronous?

Javascript is known by many as an asynchronous, non blocking programming language. However there are only certain tasks in Javascript that can be non blocking, such as fetching a request, or running code wrapped in a setTimeout or setInterval function.

The following lines of code

const some_number = 4;

console.log("Hello");

for(let i = 0; i < some_number; i++) {
  console.log(i);
}

Are synchronous, blocking Javascript. Theres no possibility where the for loop can happen before the declaration of the some_number variable

However, if we wrap the console.log statement that prints out hello world in a setTimeout with a timeout of 1000ms, you would see that the “Hello” would print to the console after the for loop. setTimeout allowed us to run code that did not block the for loop printing out numbers to the console from running.

Since both actions occurred on the same thread the main thread, the console log inside the setTimeout and the for loop do not run at the same time.

Running Javascript in multiple threads

To run different pieces of Javascript code at the same time we can run Web Workers! Web workers allow us to run Javascript to run in different threads on our CPU.