Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to call a function repeatedly every 5 seconds in JavaScript ?
Next article icon

How to run a function in a separate thread by using a Web Worker in JavaScript ?

Last Updated : 29 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a popular lightweight, interpreted compiled client-side scripting language. Most Web Applications use JavaScript on the client side. By providing JavaScript with a runtime environment, it can also be used on the server-side (Node.js). In this article, we will cover how to run a function on a separate thread by using a JavaScript Web Worker.

Pre Requisites:

  • Web Workers
  • JavaScript Functions

What is a Web Worker?

Many languages such as Java, C++ etc have the functionality of multi-threading. A web worker simply allows us to use the functionality of multi-threading in JavaScript. If any time-consuming function is blocking the DOM, we can use web workers to run it in the background keeping the DOM clutter-free.

Obstacles Faced by Web Workers:

  • A Web Worker does not have access to the DOM.
  • Data that cannot be reproduced can’t be passed to the web worker. More precisely data that cannot be cloned with the structured clone algorithm, can’t be passed to the web worker.

Passing a function to a web worker is a challenging task, as a function cannot be cloned by the structured clone algorithm. A DataCloneError is thrown when a function is passed to a web worker. 

The trick to passing functions to a web worker:

Step 1: Convert the function to be passed into a string by using the toString() method. Strings can be passed to a web worker as they can be duplicated by the structured clone algorithm. The below code converts the function to a string.

myString = myFunction.toString()

Step 2: Pass the string to the web worker.

Step 3: Convert the string back to a function inside the web worker by using the Function() constructor. The below code converts the string back to a function.

convertedFunction = new Function("return" + myString)();

Step 4: Evaluate the function.

Example: We are going to move the text GeeksForGeeks randomly. The random position is calculated by the web worker. We are going to create two files, one for the DOM and one for the web worker. 

index.html: Edit index.html in the following manner:

HTML

<!DOCTYPE html>
<html lang="en">
  
<body style="height: 90vh; width: 93vw;">
    <h1 style="color: #2f8d46; position: absolute;">
        GeeksForGeeks
    </h1>
  
    <script>
  
        // Updated the position on the DOM
        const updatePosition = (element, randomPosition) => {
            element.style.top = randomPosition[0] + "px";
            element.style.left = randomPosition[1] + "px";
        }
  
        // Calculates the random position
        const getRandomPosition =
            (height, width) =>
                [(Math.floor(Math.random() * height)),
                Math.floor(Math.random() * width)];
  
        // Creating a Web Worker
        const worker = new Worker('worker.js');
  
        // Getting the GeeksForGeeks text
        const title = document.querySelector('h1');
  
        // Updated the position on receiving 
        // the random position
        worker.onmessage = (event) =>
            updatePosition(title, event.data);
  
        // Passing the function to the Web Worker
        worker.postMessage({
  
            // Converting the function to a string
            function: getRandomPosition.toString(),
  
            // Arguments passed to the function
            arguments: [document.body.offsetHeight,
            document.body.offsetWidth, 1000]
        })
    </script>
</body>
  
</html>
                      
                       

worker.js: Edit worker.js in the following manner:

Javascript

self.onmessage = ({data}) => {
  
    // Converting the string back to a string
    const func = new Function(
        "return" + data.function
    )();
  
    // Evaluates the function and sends
    // the data back to the main file
    const timerFunction = () => {
        randomPositions = func(
            data.arguments[0], data.arguments[1]
        );
        self.postMessage(randomPositions);
    }
  
    // Runs the timerFunction at every 
    // interval specified in the arguments.
    setInterval(() => {
        timerFunction();
    }, data.arguments[2])
  
}
                      
                       

Output:

GeeksForGeeks switching to random positions on the DOM

Reference: Structured Clone Algorithm



Next Article
How to call a function repeatedly every 5 seconds in JavaScript ?

T

tejsidda34
Improve
Article Tags :
  • Geeks Premier League
  • JavaScript
  • Web Technologies
  • Geeks-Premier-League-2022
  • JavaScript-Questions

Similar Reads

  • How to execute a function when its name as a string in JavaScript ?
    To execute a function when its name is a string in JavaScript, we have multiple approaches. In this article, we are going to learn how to execute a function when its name is a string in JavaScript. Example: function myFunction() { ...}const functionName ="myFunction";Below are the approaches used to
    3 min read
  • How to run a function when the page is loaded in JavaScript ?
    A function can be executed when the page loads successfully. This can be used for various purposes like checking for cookies or setting the correct version of the page depending on the user's browser. Below are the approaches to run a function when the page is loaded in JavaScript: Table of Content
    2 min read
  • How to change the value of a global variable inside of a function using JavaScript ?
    Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed. Global Scope: Global variables can be accessed fro
    2 min read
  • How to transform String into a function in JavaScript ?
    In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to th
    3 min read
  • How to call a function repeatedly every 5 seconds in JavaScript ?
    In JavaScript, the setInterval() method allows you to repeatedly execute a function or evaluate an expression at specified intervals. This method is particularly useful for performing periodic tasks like updating a user interface or making repeated API calls. Syntax: setInterval(function, millisecon
    2 min read
  • How to store JavaScript functions in a queue and execute in that order?
    In this article, the task is to execute the functions in the order defined in the queue with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Declare the functions and use the array push() method to push the functions in the array. Later traverse the array and e
    2 min read
  • How to Delay a JavaScript Function Call using JavaScript ?
    Delaying a JavaScript function call involves postponing its execution for a specified time using methods like setTimeout(). This technique is useful for timed actions, animations, or asynchronous tasks, enabling smoother user experiences and better control over when certain operations run. There are
    3 min read
  • How to measure time taken by a function to execute using JavaScript ?
    This article will show how to measure the time taken by a function to execute using Javascript. To measure the time taken by a function to execute we have three methods: Table of Content Using the Using Date ObjectUsing the performance.now() methodUsing the console.time() methodMethod 1: Using the U
    3 min read
  • How to call a function that return another function in JavaScript ?
    The task is to call a function that returns another function with the help of JavaScript is called a Currying function, a function with numerous arguments that can be converted into a series of nesting functions with the help of the currying method. Approach:Define Outer Function:Create an outer fun
    2 min read
  • How to run a given array of promises in series in JavaScript ?
    Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after the completion of a promise. Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callba
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences