I have some socket.io emits that I'd like to provide handling for when they are taking too long to get back from the server with their promise. But I also don't want to outright time them out. I have seen this on some websites where a loading spinner will add 'This seems to be taking longer than usual' text after 10 or so seconds.
How can I add a timeout-style method to a Javascript function that will do something after a certain amount of time, but will NOT cancel the original method?
CodePudding user response:
Unless you have a global scope, you'll need to pass in two handlers
Something like this (I've generalised the flow because you've not provided enough information about your existing set up, so I hope it makes sense)
function doSocketRequest(normalHandler, tooLongHandler) {
let timer = null;
// set timeout to 5 seconds, if we hit it then trigger "tooLongHandler"
timer = setTimeout(tooLongHandler, 5000);
// When we receive our socket response for the event, clear the time and trigger "normalHandler"
socket.on('some_event_response', (response) => {
clearTimeout(timer);
normalHandler(response)
});
// Emit to server
socket.emit('some_event', ...etcetc);
}