title: How to terminate the right web worker with multiple instances of the same script
body: <p>I'm using web workers to add a custom number of countdown timers in a web page. Each timer creates an instance of the timer web worker. Everything works fine... but I'd like to terminate the web worker when the timer is equal to '00:00'. The following code, when a timer expires, terminates always the last web worker displayed in the page. How to terminate the right one?</p>
  
  <pre class="lang-js prettyprint-override"><code>$(document).ready(function() {
    $('.frequency-item').each(function(i, e) {
      children = $(e).children();
      observationLengthInMinutesId = children[1].id;
      timerId = children[3].id;
      startTimer(observationLengthInMinutesId, timerId);
    });
  });
  
  function startTimer(observationLengthInMinutesId, timerId) {
    w = null;
  
    if (typeof(Worker) !== "undefined") {
      if (w == null) {
        w = new Worker("/js/simple-timer.js");
        w.postMessage($('#' + observationLengthInMinutesId).val());
      }
  
      w.onmessage = function(event) {
        $('#' + timerId).text(event.data);
  
        //the problem is here    
        if (event.data == '00:00') {
          w.terminate();
        }
  
        /*
        I fixed in the following way but without terminating the workers! 
        I don't like it
        if($( '#' + timerId ).text() != '00:00') {
            $( '#' + timerId ).text(event.data);
        }
        */
      };
    } else {
      // Web workers are not supported by your browser
      $('#' + timerId).text("Sorry, your browser does not support Web Workers ...");
    }
  }
  </code></pre>