11import { NativeModules } from 'react-native'
22const { WebSocketModule} = NativeModules ;
33
4- let timeout ;
54let settings = {
65 /** The number of milliseconds to delay before attempting to reconnect. */
76 reconnectInterval : 1000 ,
@@ -41,6 +40,8 @@ class ReconnectingWebSocket extends WebSocket{
4140 this . reconnectAttempts = 0 ;
4241
4342 this . protocols = protocols ;
43+
44+ this . timeout = null ;
4445 }
4546
4647 _unregisterEvents ( ) {
@@ -59,25 +60,10 @@ class ReconnectingWebSocket extends WebSocket{
5960 return ;
6061 }
6162
62- clearTimeout ( timeout ) ;
63+ this . timeout && clearTimeout ( this . timeout ) ;
6364 this . reconnectAttempts = 0
6465 } ) ,
6566
66- /** @Override onclose **/
67- this . _eventEmitter . addListener ( 'websocketClosed' , ev => {
68- if ( ev . id !== this . _socketId ) {
69- return ;
70- }
71-
72- let _timeout = this . reconnectInterval * Math . pow ( this . reconnectDecay , this . reconnectAttempts ) ;
73-
74- clearTimeout ( timeout ) ;
75- setTimeout ( ( ) => {
76- this . reconnectAttempts ++ ;
77- this . reconnect ( )
78- } , _timeout > this . maxReconnectInterval ? this . maxReconnectInterval : _timeout ) ;
79- } ) ,
80-
8167 /** @Override onerror **/
8268 this . _eventEmitter . addListener ( 'websocketFailed' , ev => {
8369 if ( ev . id !== this . _socketId ) {
@@ -86,8 +72,8 @@ class ReconnectingWebSocket extends WebSocket{
8672
8773 let _timeout = this . reconnectInterval * Math . pow ( this . reconnectDecay , this . reconnectAttempts ) ;
8874
89- clearTimeout ( timeout ) ;
90- setTimeout ( ( ) => {
75+ this . timeout && clearTimeout ( this . timeout ) ;
76+ this . timeout = setTimeout ( ( ) => {
9177 this . reconnectAttempts ++ ;
9278 this . reconnect ( )
9379 } , _timeout > this . maxReconnectInterval ? this . maxReconnectInterval : _timeout ) ;
@@ -99,7 +85,7 @@ class ReconnectingWebSocket extends WebSocket{
9985 if ( this . maxReconnectAttempts && this . reconnectAttempts > this . maxReconnectAttempts ) {
10086 return ;
10187 }
102- setTimeout ( ( ) => {
88+ this . timeout = setTimeout ( ( ) => {
10389
10490 WebSocketModule . connect (
10591 this . url ,
@@ -108,10 +94,6 @@ class ReconnectingWebSocket extends WebSocket{
10894 this . _socketId ,
10995 ) ;
11096
111- timeout = setTimeout ( ( ) => {
112- this . reconnect ( )
113- } , this . timeoutInterval )
114-
11597 } , this . reconnectInterval ) ;
11698
11799 }
0 commit comments