Search code examples
javascriptnode.jssettimeoutworker-threadnode-worker-threads

Error trying to terminate worker thread using setTimeout()


When trying to terminate a worker thread using setTimeout() I get the following error:

node:internal/worker:361
    this[kHandle].stopThread();
                  ^

TypeError: Cannot read properties of undefined (reading 'stopThread')
    at Timeout.terminate [as _onTimeout] (node:internal/worker:361:19)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.12.0

Here is my code

const { Worker } = require("node:worker_threads")
const worker = new Worker("./test.js")

const setAppTimeout = (workerName, seconds) => {
    setTimeout(workerName.terminate, seconds * 1000)
}

setAppTimeout(worker, 1)

When I try terminating the worker like this it works though

const { Worker } = require("node:worker_threads")
const worker = new Worker("./test.js")

const setAppTimeout = (workerName, seconds) => {
    setTimeout(terminateWorker, seconds * 1000, workerName)
}
const terminateWorker = (workerName) => {
    workerName.terminate()
}

setAppTimeout(worker, 1)

Can someone tell me why this is the case?


Solution

  • It's because you are loosing the this context to worker when passing worker.terminate to setTimeout.

    What you can do is to .bind the .terminate method to the worker object and pass the bound function:

    const setAppTimeout = (workerName, seconds) => {
      setTimeout(workerName.terminate.bind(workerName), seconds * 1000);
    }
    

    Read more about this on MDN
    And more about .bind on MDN, too