JavaScript Easy technical 1 views 1 min read

Give an example of a web worker

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

You need to follow below steps to start using web workers for counting example

  1. Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
    let i = 0;

    function timedCount() {
      i = i + 1;
      postMessage(i);
      setTimeout("timedCount()", 500);
    }

    timedCount();
    

Here postMessage() method is used to post a message back to the HTML page

  1. Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
    if (typeof w == "undefined") {
      w = new Worker("counter.js");
    }
    

and we can receive messages from web worker

    w.onmessage = function (event) {
      document.getElementById("message").innerHTML = event.data;
    };
    
  1. Terminate a Web Worker:

Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.

    w.terminate();
    
  1. Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
    w = undefined;
    

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?