Alk
Alk

Reputation: 5547

Socket.io - Prevent multiple events from firing

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?

Upvotes: 0

Views: 429

Answers (1)

Alk
Alk

Reputation: 5547

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);
};

Upvotes: 1

Related Questions