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

198
Views
How to try to execute code at a certain interval?

I'm developing a small browser extension and I was wondering how I can try to execute code again, in case an exception was thrown because certain parts of the web site are loaded asynchronously and might not yet be ready at the time my script is executed.

If they are not ready, I want to catch the exception and try again after a certain delay. I don't want the program to loop through my code a million times per second until it is successful.

What's the best approach to this problem?

So far I've got this. Please tell me if there is a better approach or any improvements to be made:

function tryAtInterval(callback, timeout, maxAttempts) {
    let count = 0
    try {
        callback(count++)
    } catch (e) {
        if (count === maxAttempts)
            throw e
        let intervalId = setInterval(() => {
            try {
                callback(count++)
                clearInterval(intervalId)
            } catch (e) {
                if (count === maxAttempts)
                    throw e
            }
        }, timeout)
    }
}

This is quite convoluted because the setInterval function first waits for the specified amount of time and then calls the callback function the first time. I don't want the execution of my code to be delayed from the start.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I normally use setInterval when I want a consistent timer or recurring function. However, if it is intended to stop then I tend to use a recursive timeout.

function intervalCheck(callback, count = 0, maxCount, timeout) {
   if (/* your loaded logic check here */) {
     return callback();
   }

   setTimeout(function(){
      intervalCheck(callback, ++count, maxCount, timeout)
   }, timeout)
}

I believe this is far simpler and cleaner.

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!