Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
Javascript method to alert the user when a method is taking longer than expected?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);   
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda