Web Workers


Uncategorized

Updated Nov 17th, 2021

Glad I found this. Fairly easy to implement.

think of the worker as another thread
offload labor intensive work
In a worker you don’t have access to the DOM or window or global variables
pretty sure you can juts use on your local filesystem without live server running
can log to the conole from the worker but .toLocaleString Doesn’t work

Can the same worker file be used for multiple slates or does each slate need its own? Needs its own.

can addEventListeners like message and error onto the worker
Will often use the keyword “self” inside of the web worker
self.AddEventListener
self.postMessage(‘Closing the web worker’)
self.close()
no access to the DOM: the Window object and the Document object
they can only communicate back with the main JavaScript program using messaging
they need to be loaded from the same origin (domain, port and protocol)
they don’t work if you serve the page using the file protocol (file://), you need to serve them // through HTTP(S) using a web server.
Good browser support although not 100%
if (typeof Worker !== ‘undefined’) {//..workers are available}
There is an onerror we can access with event.message

Web Workers are launched and if they do not stay in listening mode for messages throughworkeronmessage or by adding an event listener, they will be shut down as soon as their code is run through completion.

A Web Worker can be stopped using its terminate() method from the main thread, and inside the worker itself using the global method close()

Can load libraries using the importScripts() global function defined in their global scope

APIs available in Web Workers
As said before, the DOM is not reachable by a Web Worker, so you cannot interact with the window and document objects. Also parent is unavailable.

You can however use many other APIs

Example

// inside a handleCLick function

  // define object to send to worker
  let workerData = {
    salaryMax,
    maxLineupsToCheck,
    minimumPts,
    sitStarts,
    trimmedAndBenchedPlayerData
  }

  // instantiate worker to run loop and send it the necessary data
  const myWorker = new Worker("worker.js")
  myWorker.postMessage(workerData)

  // Add Listener for cancel button
  cancelBtn.addEventListener("click", () => {
    generateBtn.disabled = false
    loadingContainer.classList.remove("active")
    dotsLoading.classList.remove("active")
    cancelBtn.classList.remove("active")
    myWorker.terminate()
    generateBtn.focus()
  })

  // receive the data back from the worker
  myWorker.onmessage = function (e) {
    //console.log(e.data)
    runTime = e.data.runTime
    foundLineup = e.data.testLineup
    i = e.data.i
    conditionsMet = e.data.conditionsMet
    testLineupProjectedPts = e.data.testLineupProjectedPts
    testLineupSalary = e.data.testLineupSalary
  }

In the worker itself

onmessage = function (e) {
  //define necesssary variables in worker scope
  let conditionsMet = false
  let i = 1
  let maxLineupsToCheck = e.data.maxLineupsToCheck
  let result
 

  do {
    // create Random lineup, return it to the main thread of meets conditions
    result = whatEvFunction(maxLineupsToCheck)

    // increment i to check again
    i++
  } while (i <= maxLineupsToCheck && conditionsMet == false)
  
  function whateEvFunction(maxLineupsToCheck) {
   // code here
  }

  // define object to send back
  let outputObject = {
    conditionsMet: result.conditionsMet,
    testLineup: result.testLineup,
    i: i - 1,
  }

  // send data back from worker
  postMessage(outputObject)

}