0

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?

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.