JavaScript Thread
Posted by Superadmin on May 01 2023 10:28:39

JavaScript Thread

JavaScript Thread

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:

JavaScript thread 1

After 5000 milli seconds, an undefined value is generated, and then the value ‘Anusha’ is printed in the console.

JavaScript thread 2

Explanation:

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:

JavaScript thread 4

Based on setTimeout timers, the rest of the data is printed on the console.

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:

JavaScript thread 6

On clicking on Start Count, Count would be increased after each setTimeout.

Count would be increased after each setTimeout

On clicking on the stop, the counter would stop increasing be static.

On a wide note, let’s summarize the above example with the syntax used; how web workers work?

var worker = new Worker("sample.js");
importScripts("sample.js", "sample1.js");
worker.terminate()
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.