P5.js basic webworkers tutorial

Hi! I am having a bit of trouble getting webworkers to properly work with P5.js
is anyone familiar with a basic getting started tutorial in P5.js?

Here is a basic sketch but somehow the old response gets stuck in the browsers memory or something and I don’t know how to clear it. Here is my code.

main.js

function setup() {
  createCanvas(10, 10);
  workers = new Worker('worker.js');
  workers.onmessage = workerDone;
  workers.postMessage({
    message_1: 'first message',
    message_2: 'another message'
  });
}

function draw() {
}

function workerDone(e) {
  console.log(e.data);
}

worker.js

this.onmessage = function(e){
  
  var response_1 = "sending something back!!";
  var response_2 = "sending some other thing back!";
  
  this.postMessage({response1:response_1, response2:response_2});
};

Any help would be appreciated. Thanks!!

Hi! Welcome to the forum!

Can you be more specific about what the problem is, by “stuck in memory” ? I run the code (I had to do it locally as I couldn’t find a way to access worker.js on web editor) but the code only bounces back the message so I couldn’t understand what you mean.

Also since p5.js is not intended for exploring every javascript feature so the tutorial you are looking for may not exist :frowning:

Hi @micuat! Thank you for your response. It is interesting that it was working for you locally. Are you able to run the code a few times, but each time changing the response to something else.

i.e. response_1 = “sending something else this time”.

Whenever I run the code in the web editor it returns an old response that is stuck in the browsers cache or something. Not entirely sure how to work around this.

Here is a link to the online editor version : link

Thank you!

P.S. I just tested this locally and I still have the same issue :face_with_raised_eyebrow:

Image for clarification

I was able to solve this locally by adding versioning to the .js file

<script src = "filename.js?version = 1.0" >

Note: This doesn’t work with the P5 online editor :smiley:
Thank you @micuat

thanks I tested now. Here are some observations:

  • the web editor code doesn’t run on Firefox. The js file is served as text/html and it seems not allowed to load as a worker (not sure if this relates to the web editor)
  • somehow the web editor works on Chrome. I could replicate your issue. When this happens, this file seems not updated (and this is not browser cache - try ctrl/cmd+shift+R to delete cache and refresh), which explains the issue: https://editor.p5js.org/kris.dpd/sketches/TFylH-TRf/worker.js
  • running the code locally works fine on both Firefox and Chrome. Note that I use live-server from npm. In this case you cannot open the file directly from explorer/finder (reference)