xxxxxxxxxx
72
const worker =
{
ID: null,
Initialized: false,
Waiting: false,
WaitDuration: 0,
ProcessMessage: function(e)
{
const functionName = "On" + e.data.Key + "Received";
if (!this[functionName].call) return;
this[functionName](e.data.EventData);
},
OnInitializeReceived: function(eventData)
{
if (this.Initialized) return;
this.Initialize(eventData);
},
Initialize: function(eventData)
{
this.Initialized = true;
this.ID = eventData.ID;
console.log(`Worker ${this.ID} initialized`);
},
OnWaitReceived: function(eventData)
{
if (this.Waiting) return;
this.Wait(eventData);
},
Wait: async function(eventData)
{
this.Waiting = true;
this.WaitDuration = eventData.WaitDuration;
await Delay(this.WaitDuration);
this.Finish(eventData);
},
Finish: function(eventData)
{
const outgoingData =
{
Key: "WorkerFinished",
EventData:
{
Worker: this,
},
};
postMessage(outgoingData);
this.Waiting = false;
},
};
onmessage = worker.ProcessMessage;
const Delay = async function(ms) { return new Promise((r) => setTimeout(r, ms)) }