0

I'm trying to create 7 Javascript shared workers inside a for loop. My IDE (Pycharm) is giving me a warning for these two variables container-frame and worker:

"Mutable variable is accessible from closure"

Each of these shared worker is communicating with network_worker.js

Below is my JS code:

socket = io.connect('http://' + document.domain + ':4999/layout');
// Set up CSS
for (var i=0; i<player_dict.length; i++) {
    var _id = player_dict[i]['_id'];
    var container_frame = document.getElementById("container-frame-" + _id);
    container_frame.style.display = "none";

    setup_communication();
    console.log(_id)
    var client_id = _id;
    var alarm_flag= "";
    var alarm_metric="";
    if (client_id != null && client_id == 0 && parseInt(location.port) == 4999) {  // player_0_hack (for now). Remove and have work properly.
        label = "";
    } else if (client_id != null){
        label = "Service " +  (parseInt(location.port) - 5000 + 1);
    } else {
        label = "Invalid player id";
    }
    var worker = new SharedWorker('../static/js/network_worker.js', client_id);
    console.log(worker);
    worker.port.addEventListener('message', worker_callback, false);

    window.addEventListener("beforeunload", function () {
        worker.port.postMessage('label_close');
    });
    worker.port.start();

    function worker_callback(e) {
        console.log(e.data)
        if(e.data.type == "update_label") {
            console.log(container_frame)
            container_frame.style.animationDuration =  Math.random() + "s";
        }
    }

    worker.port.postMessage({type: "label_connection", payload: {domain: document.domain, port: location.port, client_id: client_id, label: label}, alarm_flag: alarm_flag, alarm_rate: 1, alarm_metric: alarm_metric});
}

Ultimately what I'm trying to do is animating the container-frame for 7 HTML elements. I'm iterating over these elements using the for loop. These animations happen when an event is triggered from a JS script (update label).

Currently, I have 7 HTML elements. The last element only is having the animation working properly.

My doubt is that when I have put the worker_callback function inside the for loop, the JS compiler became confused about the scope of container_frame but I'm not sure.

Any suggestions please ?

Joseph Wahba
  • 660
  • 3
  • 9
  • 25

1 Answers1

0

The problem was the two variables container_frame and worker where defined as var not const. Thanks to @Edmund Lee

Joseph Wahba
  • 660
  • 3
  • 9
  • 25