Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js

    Programming

    3. Express.js Lessons. Templating with EJS: Layout, Block, Partials

    Programming

    Programming Patterns. Introduction

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Thursday, October 16
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / Web Workers: Concurrency In Java Script
    Programming

    Web Workers: Concurrency In Java Script

    Stepan ZharychevBy Stepan ZharychevFebruary 15, 2018Updated:April 5, 2019No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Web Workers: Concurrency In Java Script
    Web Worker is a modular script that runs separately from the main JS thread (a thread that normally includes all the scripts of your web application) and communicates with it using events only.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    There are lots of articles that explain and describe concurrency in JS from different angles. Ours will be practical enough to start using concurrency immediately. First, let’s look at the questions and answers about JS nature.

    • Is concurrency possible in JS as a language itself? – No, it’s not. Java Script is single-threaded programming language with asynchronous operations support. (It can all live together because of the tricky queue/event management system.)
    • Am I doomed if there’s a need for heavy operation handling in a JS application? – Again, no! There’s a great way to move the effort from the main thread away using something else…

    … and this something else is our today’s hero – Web Worker!

    In short, Web Worker is a modular script that runs separately from the main JS thread (a thread that normally includes all the scripts of your web application) and communicates with it using events only. There’re a few specific features that come from such a definition:

    worker-specifics

    For better understanding, we’re going to create a small application with a very simple task: it’s going to calculate prime numbers until a given position, returning the feedback about the current state and progress to the main thread.

    I’ve chosen this example because the prime number calculation algorithm is pretty heavy and can be a great tester for our worker, especially in its unoptimized form. We’re also going to show the list of requested states which will be fully scrollable and extendable with new statuses while Worker’s doing heavy calculations behind.

    But let’s begin with the technical aspect and see how we can enable Web Worker:

    let worker = new Worker('<your_worker_uri>.js');

    One problem arises immediately. In current web development practices, all the scripts are normally minified and downloaded by the browser as a bundle (I mean popular frameworks, like Angular and React, which are commonly used with bundlers, like Webpack), while Web Worker constructor needs an absolute address of the script. Below we’re going to analyze a solution that’s suitable for Webpack + TypeScript  (but can also be used with plain JS):

    To include Web Worker sources into your bundle, you need to use worker loader in the following way:

    import Worker from 'worker-loader!./<your_worker_uri>.js';

    For TS integration, the process is a bit trickier:

    1. You need to specify module for worker loader definition (the easiest way is to specify [hash] variant of this module as a generic one, you can read about hash definition on the loader page, but, in simple words, it just generates hash-based name for loader during the bundling):
      declare module 'worker-loader?name=dist/[hash].js!*' {
          const value: any;
          export = value;
      }
    2. Import worker using hash notation:
      import Worker from 'worker-loader?name=dist/[hash].js!<your_worker_uri>'&nbsp;
      

    Basically, that’s it. Worker can be written on JS or TS, and it doesn’t matter if the latter was included into webpack.config.js correctly. Don’t forget that you can and probably should import dependencies with such bundling through the import, so it’s not necessary to write all the logic inside one file.

    Read More:  Overview of Basic Data Structures: How to Organize Data the Efficient Way

    After Web Worker is successfully attached, you can start with communication structuring. In the simplest case, communication will look like this:

    worker-process-basic

    Obviously, in both cases cases you should listen for the ‘message’ event using addEventListener and act accordingly like this:

    self.addEventListener('message', message => {
    // Here goes code of your listener...
    }

    By the way, in this example of code, we do listening for changes inside worker and variable self is a context of Worker where all the functionality lives. And here you can see another blurry specific of Workers: message event data is fully generic, so differentiation of such events fully lies on you. We wanted to support returning of the current progress state from Worker back to the main thread (at least to show valid progress bar and log statuses), which makes our chart a bit more complicated:

    worker-process-state-back

    This scheme can be even more complicated if you want to process more than one task inside one worker or ping the main thread with a different kind of details. But the universal recipe is to use the following structure of the ‘message’ event data inside your application:

    WorkerInput {
        type: string; // or enum preferably
        arg: any;
    }

    Type property says what event we’re going to handle, while arg property contains all the required data for this kind of event. For example, in the upper case the code would be:

    • For init worker event:
      primeWorker.postMessage({
          type: WorkerInputType.start,
          arg: {
              mode: WorkerMode.log,
              position: 100001
          }
      });v
    • For sending of current status back:
      sendMessage({
                  type: WorkerResponseType.status,
                  data: (this.active ? {
                      active: true,
                      position: this.currentPosition,
                      prime: this.currentPrime,
                      percentage: Math.floor(this.currentPosition / this.targetPosition * 100)
                  } : {
                      active: false
                  })
              });
      

       

    The logic of handling for each individual type of event can be done with common switch and multiple handlers in the case of few simple operations (our case), but if you’re going to have a set of complicated algorithms behind event types in Worker, I would recommend you to use strategy pattern.

    Now that we know how to send and receive data successfully, we can easily optimize the prime number calculation with Worker (any other heavy algorithm can be optimized in such way). The steps are:

    1. Move the whole algorithm that freezes the main thread inside the Worker;
    2. Add proper event handlers on both sides of communication (for the main thread those handlers will change DOM accordingly, e.g. move progress bar or add log into the list);
    3. If you plan to use Worker from the different parts of your app, control the number of instances (singleton class as a shell for Worker can be a good idea) not to initialize the same process twice;

    I want to emphasize that Web Worker is not a silver bullet for any performance issue in your app. The reasons of page freezes can be very different, from implementing a memory leak to overloading your framework with heavy DOM operations. When you see freezes, it doesn’t mean, “It’s Web Worker time!” Check your code first, and only if you see that a specific part is causing a performance issue, you can try to move it aside via Web Worker. (But to be honest, you should know about such heavy calculations at the very beginning of your project, when you plan everything.)

    The full code example can be found here. Thanks for your attention!

    We are looking forward to meeting you on our website blog.soshace.com

    Read More:  RxJS Introduction
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Stepan Zharychev
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Interview March 15, 2019

    20 JavaScript Interview Questions – Part 2

    We continue the series with JavaScript interview questions, where we cover theoretical and practical questions (ES5)

    Mastering N-API and Native Modules in Node.js

    February 13, 2024

    Create a Simple POS with React, Node and MongoDB #0: Initial Setup Frontend and Backend

    January 7, 2020

    Key Strategies for Successful Influencer Partnership Negotiations

    August 27, 2025

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    React Lesson 7: Redux

    JavaScript January 10, 2020

    How Google, Apple, and Other Tech Companies Organize Their Remote Teams

    Remote Job April 10, 2019

    Effective Strategies for Managing Scope Creep in Projects

    JavaScript November 26, 2024

    How to setup SonarQube in a project on Local Machine.

    Programming April 30, 2023

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Beginners

    What Is Responsive Web Design?

    Python

    Creating Real-Time API with Beautiful Soup and Django REST Framework

    SEO & Analytics

    Strategies to Mitigate Duplicate Content in Programmatic SEO

    Most Popular

    Introduction to GitHub Desktop: A GUI Enhancement to a CLI Approach

    Git

    React Lesson 2: Homework Assignment

    JavaScript

    Build Real-World React Native App #6: Show Bookmark and Categories

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.