Updated April 15, 2023
Introduction to JavaScript Thread
In software, ‘Thread’ is the smallest sequence of execution of programmed instructions managed independently by a scheduler, being a part of an Operating System. JavaScript Thread is single-threaded by default used to run a script in the web application, perform layout and garbage collection. Being single-threaded is to execute only a single set of instructions at any time in the process. This was the main drawback in JavaScript which led to the implementation of Server-side Asynchronous I/O, which would help us in multi-threading by reducing race among the threads.
Let us see how ‘JavaScript Thread’ has evolved? In JavaScript, we have loops for executing functions, but that itself was not enough for longer executing functions. For example, if we want to execute our process with 60FPS, only 16ms are left to execute the code before the next code frame. JavaScript does not support multi-threading as the JavaScript interpreter in the browser is single-threaded. Even our famous Web browser, Google Chrome, will not let a single JavaScript page run concurrently as it could cause issues in the application. One single thread handles the entire event cycle. So, JavaScript has introduced a new concept here for the limitation we are facing, i.e., Web Workers.
Web Workers can perform long-running tasks without affecting the thread of execution. A worker is an object created using Constructor, which will run a JavaScript file. This JavaScript file contains code which will run in a worker thread; these workers run in another global context which differs from the current window.
Examples of JavaScript Thread
Given below are the examples of JavaScript Thread:
Example #1
JavaScript Single Thread.
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Single Thread</title>
</head>
<body>
<script>
document.write("Karthick ")
setTimeout(() => {
document.write("Anusha")
}, 5000)
document.write("Samuel")
</script>
</body>
</html>
Output:
After 5000 milli seconds, an undefined value is generated, and then the value ‘Anusha’ is printed in the console.
Explanation:
- Write(‘Karthick’) will be printed first as it’s on the stack first.
- Then JavaScript engine notices setTimeout which is not handled by JavaScript and pushes it to WebAPI for asynchronous execution.
- The next data printed on the console is ‘Samuel’ without caring about the code handled over to WebAPI.
- After this, the JavaScript engine gets into the picture, waiting for events to load until events are completed and setTimeout waits for 5000 milli seconds, undefined is printed( Here, in console undefined is not printed but will consume some time).
- Finally, once the timeout is done, it will print the value ‘Anusha.’
Example #2
Using Asynchronous AJAX calls instead of Web Workers.
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Single Thread</title>
</head>
<body>
<script>
document.write("ABC ");
setTimeout(function(){
document.write("MNO ");
},0);
document.write("DEF ");
setTimeout(function(){
document.write("JKL ");
},2000);
document.write("GHI ");
setTimeout(function(){
document.write("PQR ");
},3000);
</script>
</body>
</html>
Output:
Based on setTimeout timers, the rest of the data is printed on the console.
Example #3
Web Workers.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Count: <output id="resultNum"></output></p>
<button onclick="startWorker()">Start Count</button>
<button onclick="stopWorker()">Stop Count</button>
<script>
var num;
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(num) == "undefined") {
num = new Worker("demo_workers.js");
}
num.onmessage = function(event) {
document.getElementById("resultNum").innerHTML = event.data;
};
} else {
document.getElementById("resultNum").innerHTML = "Something went wrong.... Your browser might nto support Web Workers";
}
}
function stopWorker() {
num.terminate();
num = undefined;
}
</script>
</body>
</html>
In demo_workers.js file
var i = 0;
function counter() {
i = i + 1;
postMessage(i);
setTimeout("counter ()",500);
}
counter();
Output:
On clicking on Start Count, Count would be increased after each setTimeout.
On clicking on the stop, the counter would stop increasing be static.
- We would create a web Worker file and write our counter logic, which is stored as a demo_workers.js file.
- The most important part of code is postMessage(), used to post messages back to an HTML page.
- Then we need to create a Web Worker object to call the web worker file to the HTML page.
- We need to have an event listener ‘onmessage’ here used to send and receive messaged from a web worker.
- So when the web worker posts any message, the event listener executes its code and stores data in event.data.
- To terminate the web worker or release the computer resources, we are using the .terminate() method.
- We can reuse this code if we set the worker variable to undefined after terminating the web worker.
On a wide note, let’s summarize the above example with the syntax used; how web workers work?
- WebWorkers get initialized with URL of JavaScript file, which contains logic worker will execute
var worker = new Worker("sample.js");
- If the .js file exists, the browser will make a new thread downloaded asynchronously; else would return a 404 error and fail.
- Multiple JavaScript files can also be imported.
importScripts("sample.js", "sample1.js");
- Once this connection is working, communication between web Workers is done using the postMessage() method.
- Any data passed by Web Worker is accessed using onmessage event.
- The main html page will spawn a web Worker to execute the code and produce results.
- To Terminate the Web Worker.
worker.terminate()
- A terminated worker will no longer respond to any kind of computations.
- We can also handle errors here using.
worker.onerror()
Conclusion
We have seen Single Threading in JavaScript with few examples. Multi-Threading being possible with asynchronous AJAX calls. And also have seen a new concept, Web Workers, to implement Multi-Threading in JavaScript. Illustrated an example on the same with a good explanation. With Threading, work is shared into multiple threads and memory. We can achieve highly efficient services with Threading. Web Workers help in accessing the web and mobile browser environments with strict execution environments. May force users to copy objects between multiple threads and let us plan our application accordingly.
Recommended Articles
This is a guide to JavaScript Thread. Here we discuss the introduction to JavaScript Thread along with examples, respectively. You may also have a look at the following articles to learn more –