Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!