This util helps in executing tasks on dedicated worker thread in runtime with ease. Utilizes the string template literals to accept a function in string format. A JS file is created using this function to initialize the Worker thread.
Every function spawns a new worker thread. Once the task is done the thread is destroyed.
npm install webworker-utilProcess objects/arrays in worker thread to reduce load on render thread.
import{worker}from"webworker-util";constme={name: "lokesh",lname: "pathrabe"};constresult=awaitworker`(function(person){ return person.name.concat(person.lname) })(${me})`;console.log(result);// logs lokeshpathrabemake API calls in worker thread
import{worker}from"webworker-util";constresult=awaitworker`(async function(){ const fetchData = new Promise((resolve) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { resolve(xhttp.responseText); } }; xhttp.open("GET", "filename", true); xhttp.send(); }); const data = await fetchData; return data;})()`;});execute some code in setInterval. Since webworker threads are not affected by resource throttling done by browsers, they are perfect place to execute time sensitive operations
import{createIntervalWorker}from"webworker-util";constcallback=jest.fn((v)=>{console.log(v);});constintervalWorker=createIntervalWorker(callback,1000);constclearInterval=intervalWorker`(function(){ return new Date(); })()`;awaitwait(100000);// execute for sometimeclearInterval();// Dont forget to clear the interval