WebSocket reconnect loop in Node.js Genesys Notification API

The connection drops every few minutes and my manual reconnect logic triggers a massive loop. Here’s the snippet I’m using to handle the close event. It keeps firing and I can’t figure out why the state isn’t resetting properly. Any ideas on how to debounce this?

ws.on('close', () => {
 console.log('Connection lost');
 setTimeout(() => connect(), 5000);
});