Skip to content

'Web workers' do not work in editor #3414

Closed
@quarks

Description

@quarks

p5.js version

1.11.1

What is your operating system?

Mac OS

Web browser and version

Firefox 136.0.2 (64bit) & Safar 18.3.1i

Actual Behavior

Although it is possible to create a web worker object, posting and receiving messages from it does not appear to work.

I have created a simple sketch in the editor to demonstrate the problem.

Expected Behavior

The sketch should display a randomly display a rectangle every 2 seconds, it uses a web worker to calculate the position and size and send the information back to the main sketch. This works as expected using VSC but fails in the web editor.

Steps to reproduce

Steps:

I have included the code below but it is easier to see it in action in the editor here.

Snippet:

main.js

let worker, n = 1, x = 0, y = 0, w = 0, h = 0;

function setup() {
    p5canvas = createCanvas(320, 240);
    worker = new Worker('worker.js');
    worker.onmessage = (e) => { processMessage(e.data) };
    worker.postMessage(`Rectangle ${n++}`);
    setInterval(() => { worker.postMessage(`Rectangle ${n++}`); }, 2000)
}

function processMessage(info) {
    [x, y, w, h] = [info.x, info.y, info.w, info.h];
}

function draw() {
    background(255, 240, 255);
    fill(255, 170, 100); stroke(0); strokeWeight(3);
    rect(x, y, w, h);
}

worker.js

onmessage = function (message) {
    let x = 50 + Math.floor(Math.random() * 100);
    let y = 20 + Math.floor(Math.random() * 100);
    let w = 100 + Math.floor(Math.random() * 100);
    let h = 50 + Math.floor(Math.random() * 50);
    postMessage({ action: 'done', x: x, y: y, w: w, h: h });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugError or unexpected behaviors

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions