0

I have a socket.io connection setup between my iOS app and my nodeJS backend.

Upon connection, I setup my socket like this:

 socket.on(EVENT_NAME1, params => someFunc(socket, params) ); socket.on(EVENT_NAME2, params => someOtherFunc(socket, params) ); socket.on(EVENT_NAME3, (params, callback) => someThirdFunc(socket, params, callback) ); ... 

The problem is, sometimes my iOS app fires multiple events and I'd like to ensure on the backend, that if several of the same events arrive from one socket within 250ms only the first one gets executed.

I created this function:

const timeoutEvent = (eventName, socket, params, callback, func) => { socket.off(eventName); setTimeout(() => { if (callback) { socket.on(eventName, (params, callback) => { func(socket, params, callback); }); } else { socket.on(eventName, params => { func(socket, params); }); } }, 250); }; 

which I want to use like this:

socket.on(EVENT_NAME3, (params, callback) => { timeOutEvent(EVENT_NAME3, socket, params, callback, someThirdFunc) someThirdFunc(socket, params, callback); }) 

The problem with this is that these lines won't work, as the eventName, params and callback are coming from the on function and not from the higher level timeoutEvent function -

socket.on(eventName, (params, callback) => { func(socket, params, callback); }); 

How can I adjust the above code to fit this purpose?

1
  • From what I understand, consume the message. Have a flag set that once you get a message you set it to a value and it should go back to the original values after 250 ms. While the flag value is set to another value in those 250 ms, consume the message but do not do anything! Commented Apr 13, 2020 at 1:07

1 Answer 1

1

In my connect function, I added:

socket.enabled = true socket.on(EVENT_NAME, (params, callback) => { socket.enabled && someFunc(socket, params, callback); preventMutlipleHandlers(socket); }); 

and then I created this func:

const preventMutlipleHandlers = socket => { socket.enabled = false; setTimeout(() => { socket.enabled = true; }, 250); }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.