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?
It's because you are loosing the
thiscontext toworkerwhen passingworker.terminatetosetTimeout.What you can do is to
.bindthe.terminatemethod to theworkerobject and pass the bound function:Read more about
thison MDNAnd more about
.bindon MDN, too