diff --git a/index.js b/index.js index d0d3de5..5f95820 100644 --- a/index.js +++ b/index.js @@ -637,6 +637,20 @@ class ModbusRTU extends EventEmitter { return false; } + /** + * Clears the timeout for all pending transactions. + * This essentially cancels all pending requests. + */ + _cancelPendingTransactions() { + if (Object.keys(this._transactions).length > 0) { + Object.values(this._transactions).forEach((transaction) => { + if (transaction._timeoutHandle) { + _cancelTimeout(transaction._timeoutHandle); + } + }); + } + } + /** * Close the serial port * @@ -661,6 +675,9 @@ class ModbusRTU extends EventEmitter { * or failure. */ destroy(callback) { + // cancel all pending requests as we're closing the port + this._cancelPendingTransactions(); + // close the serial port if exist and it has a destroy function if (this._port && this._port.destroy) { this._port.removeAllListeners("data");