diff --git a/lib/noble.js b/lib/noble.js index 13166b99..dc5d1425 100644 --- a/lib/noble.js +++ b/lib/noble.js @@ -167,6 +167,7 @@ class Noble extends EventEmitter { return; } const timeoutId = setTimeout(() => { + this.removeListener('stateChange', listener); reject(new Error('Timeout waiting for Noble to be powered on')); }, timeout); diff --git a/test/noble.test.js b/test/noble.test.js index 88f9fd56..35736c24 100644 --- a/test/noble.test.js +++ b/test/noble.test.js @@ -420,6 +420,19 @@ describe('noble', () => { // Promise should reject after timeout await expect(promise).rejects.toThrow('Timeout waiting for Noble to be powered on'); }); + + test('should not cause MaxListenersExceededWarning with multiple timeout calls', async () => { + noble._state = 'poweredOff'; + + const promises = []; + for (let i = 0; i < 11; i++) { + promises.push(noble.waitForPoweredOnAsync(0).catch(() => {})); + } + await Promise.all(promises); + const finalListenerCount = noble.listenerCount('stateChange'); + + expect(finalListenerCount).toBeLessThanOrEqual(1); + }); }); test('should change address', () => {