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 JavaScript Works?
Next article icon

Web Workers in Javascript

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Web workers are giving us the possibility to write multi-threaded Javascript, which does not block the DOM. Even the Asynchronous operations block the DOM to some extent. On the other side, web workers help us solve this problem, escaping the single-threaded environment and reaching a higher performance of our web pages.

In order to use:

  • Web workers live in their own file (Not interacting with the User Interface)
  • Functions are Passed By Copy
  • No global variables are allowed
  • Implementing Web Workers

    javascript
    /* -----------------------------Index.JS--------------------------*/    // Check if web worker functionality is available for the browser         if(window.Worker){                      // Creating new web worker using constructor             var worker = new Worker('worker.js');                                       var message = 'Hello';                      // Sending the message using postMessage             worker.postMessage(message);                          // On response             worker.onmessage = function(e) {                 console.log(e.data);             };                  }   /* -----------------------------Worker.JS--------------------------*/  // Waits for any activity from the page self.onmessage = function(e) {     if(e.data !== undefined) {         // Do work          var total = e.data + ' World';         // Posting back to the page         self.postMessage(total)     } } // Terminate with: worker.terminate() 

    In the example above, the worker is doing the work of concatenating the received string with the defined one and sends it back to the main.js file without interrupting the page.

    Output :'Hello World'

    Web Workers does not have access to:

  • The Parent Object
  • The Window Object
  • The Document Object
  • The DOM

  • However, the do have access to:

  • The location object
  • The navigator object
  • XMLHttpRequest
  • The Application Cache
  • Spawning other web workers (Stored at the same origin as the parent page)
  • Importing external script using importScripts()

  • Common use cases:

  • When complex computing calculations are required
  • In HTML5 Games (Higher frame rate)
  • At any websites containing JavaScript for performance improvement

  • Real World Example

    The following program is written for the reason to show what difference is in the behavior of our page with and without worker.

    javascript
    /* -----------------------------Index.JS--------------------------*/ const delay = 5000;  // Get element of without worker button const noWorkerBtn = document.getElementById('worker--without'); // Add event listener to the button itself noWorkerBtn.addEventListener('click', () => {     // Define the starting time     const start = performance.now();     // Do complex calculations     while (performance.now() - start < delay);     // Get the ending time     const end = performance.now();     // Calculate the difference in time     const resWithoutWorker = end - start;     // Log the result     console.log('No worker:', resWithoutWorker);      });  // Define a worker const worker = new Worker('./worker.js');  // Get element of with worker button const workerBtn = document.getElementById('worker--with');  // Add event listener to the button workerBtn.addEventListener('click', () => {     // Send delay number     worker.postMessage(delay);      }); // On message from worker worker.onmessage = e => {     // Log the result     console.log("With worker: ", e.data); };  /* -----------------------------Worker.JS--------------------------*/  // On message received this.onmessage = e => {     // Delay equals to data received     const delay = e.data;     // Define starting time     const start = performance.now();     // Do the complex calculation     while (performance.now() - start < delay);     // Get ending time     const end = performance.now();     // Calculate difference     const resWithWorker = end - start;     // Send result     this.postMessage(end - start); }; 

    Examples:

    Output: 'No worker: 5000'
    Output: 'With worker: 5000'

    That’s how the page behaves without our worker code:

  • The animation freezes because the JavaScript is blocking the DOM.
  • That’s how the page behaves with our worker code:

    https://media.geeksforgeeks.org/wp-content/uploads/20240730230501/p1.mp4
  • As you can see the animation in the background is not interrupted as our worker does the calculation for us. In this way, we let the DOM thread run independently.
  • https://media.geeksforgeeks.org/wp-content/uploads/20240730230443/p2.mp4


    Next Article
    How JavaScript Works?

    M

    MihailYonchev
    Improve
    Article Tags :
    • JavaScript
    • Web Technologies
    • JavaScript-Questions

    Similar Reads

    • How JavaScript Works?
      JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
      14 min read
    • Window Object in JavaScript
      In JavaScript, the Window object represents the browser window that contains a DOM document. The Window object offers various properties and methods that enable interaction with the browser environment, including manipulating the document, handling events, managing timers, displaying dialog boxes, a
      5 min read
    • Uses of JavaScript
      JavaScript is a versatile programming language extensively used in web development. It empowers interactive features like form validation, dynamic content updates, and user interface enhancements. Furthermore, it's employed in server-side scripting, mobile app development, game development, and even
      3 min read
    • What is JavaScript?
      JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
      6 min read
    • JavaScript Hello World
      The JavaScript Hello World program is a simple tradition used by programmers to learn the new syntax of a programming language. It involves displaying the text "Hello, World!" on the screen. This basic exercise helps you understand how to output text and run simple scripts in a new programming envir
      2 min read
    • JavaScript Common Mistakes
      JavaScript is an easy language to get started with, but achieving mastery takes a lot of effort, time, and patience. Beginners often make a few well-known mistakes. In this article, we’ll cover some of the most common learning mistakes people make and find out how to overcome them. Many of these tip
      4 min read
    • JavaScript | Top 10 Tips and Tricks
      For web development or cross-platform development, JavaScript is gaining wide popularity. Once it was considered only as a front-end scripting language but it's now getting popularity as the back-end too. Even Facebook's React Native is based on JavaScript. Hence it would surely be beneficial to kno
      7 min read
    • JavaScript History, Versions
      JavaScript, a high-level, dynamic, and interpreted programming language, is renowned for its pivotal role in web development, enabling interactive and dynamic web pages. Its creation and evolution are integral to the history of the web. Developer and Initial DevelopmentDeveloper: JavaScript was crea
      3 min read
    • How to take user input in JavaScript?
      Interacting with users is the best way to create engaging and dynamic web applications. Taking user input allows your applications to be interactive and responsive. Here we will see the approach to take user input in JavaScript, specifically using the prompt method, which is perfect for beginners. A
      3 min read
    • Getting Started with JavaScript
      JavaScript is a lightweight, single-threaded, dynamically typed, interpreted programming language with object-oriented capabilities. Primarily JavaScript is used to add interactivity and dynamism to web pages. It breathes life into static HTML and CSS, enabling features like dynamic content updates,
      8 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