Doing intensive work on a worker other than UI thread

Hello,

In my game, at start I need to compute user’s state and iterate it to calculate passage of time. In some cases calculation takes ~ 400ms, during that time UI thread completely stops. I need a way to offload that work to a worker thread so I can show some animations to the user who then can understand the game has not freeze. I tried to read pipeline.js as cc.loader doing loading without freezing the main thread, but I am not sure. Is there a supported way to do this?

JS is single threaded and any function calls, loops, etc., get executed in order. What you want is some kind of algorithm that defers calculations in some way. either using Promises for data loading, or deconstructing your algorithm away from the update call.

it’s kinda complex but you want to use the engines schedule calls in order to schedule part of your calculation, then determine how much of it you can do and still get the next frame, and then setup the schedule so that when it finished you schedule the next part of your calculation.

Here is the principle with some psuedo code

this.deconstructIterator = 0;
this.scheduleOnce(() => this.calculation(this.deconstructIterator), 0);
this.calculation = (state) => {
    partialData = this.data[state];
    //TODO data stuff
    this.deconstructIterator++;
    if (this.deconstructIterator < this.deconstructMaximum) {
        this.scheduleOnce(() => this.calculation(this.deconstructIterator), 0);
    } else {
        this.finish();
    }
}

Actually that is what I was looking for, I split up work into chunks roughly each can be completed under a frame on a reasonable phone and used scheduleOnce to queue the next piece of work. Rendering and animations can now happen between those chunks. Thanks skara.

1 Like