+ public setDefaultTaskFunction (name: string): boolean {
+ if (typeof name !== 'string') {
+ throw new TypeError('name parameter is not a string')
+ }
+ if (name === DEFAULT_TASK_NAME) {
+ throw new Error(
+ 'Cannot set the default task function reserved name as the default task function'
+ )
+ }
+ if (!this.taskFunctions.has(name)) {
+ throw new Error(
+ 'Cannot set the default task function to a non-existing task function'
+ )
+ }
+ try {
+ this.taskFunctions.set(
+ DEFAULT_TASK_NAME,
+ this.taskFunctions.get(name)?.bind(this) as WorkerFunction<
+ Data,
+ Response
+ >
+ )
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ /**
+ * Worker message listener.
+ *
+ * @param message - The received message.
+ */
+ protected messageListener (message: MessageValue<Data, Data>): void {
+ if (message.workerId === this.id) {
+ if (message.ready != null) {
+ // Startup message received
+ this.sendReadyResponse()
+ } else if (message.statistics != null) {
+ // Statistics message received
+ this.statistics = message.statistics
+ } else if (message.checkActive != null) {
+ // Check active message received
+ message.checkActive ? this.startCheckActive() : this.stopCheckActive()
+ } else if (message.id != null && message.data != null) {
+ // Task message received
+ this.run(message)
+ } else if (message.kill === true) {
+ // Kill message received
+ this.stopCheckActive()
+ this.emitDestroy()
+ }
+ }
+ }
+
+ /**
+ * Sends to the main worker the ready response.
+ */
+ protected sendReadyResponse (): void {
+ !this.isMain && this.sendToMainWorker({ ready: true, workerId: this.id })
+ }
+
+ /**
+ * Starts the worker check active interval.
+ */
+ private startCheckActive (): void {
+ this.lastTaskTimestamp = performance.now()
+ this.activeInterval = setInterval(
+ this.checkActive.bind(this),
+ (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
+ )
+ }
+
+ /**
+ * Stops the worker check active interval.
+ */
+ private stopCheckActive (): void {
+ this.activeInterval != null && clearInterval(this.activeInterval)
+ }