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

197
Visualizações
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 Respostas
Responde à pergunta

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 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