Try-catch in loop causing error

1

I have the following code, which tries to click a button after 60 seconds, and if it has not loaded, try again after 60 seconds.

    while(true) {
      var timeout = setTimeout(function() {
        try{
          document.querySelector('.department-info').click()
        } catch(e) {
          console.log('Retrying in 60 seconds...') //error handling
        }
      }, 60000)
    };

The problem is that it is not entering catch() and is, after a few lag runs, causing the page to lock and close. Can you help me? What is being done wrong?

    
asked by anonymous 10.12.2018 / 15:03

1 answer

3

Do not use while for this, use a function. While is asynchronous with setTimeout and will generate a process bottleneck, causing the locking. Using a function you can do it in a synchronized way, just calling the setTimeout again after the set time:

(function checa(){
   setTimeout(function() {
     try{
       document.querySelector('.department-info').click()
     } catch(e) {
       console.log('Retrying in 60 seconds...') //error handling
       checa(); // chama novamente a função após o tempo
     }
   }, 60000)
})(); // função auto-executada

Test 2 seconds:

Clicking on body will insert the button with class .department-info and trigger the click:

$("body").click(function(){
   $(this).html('<button class="department-info" onclick="alert(\'Clicado\')">OK</button>')
});

(function checa(){
   setTimeout(function() {
     try{
       document.querySelector('.department-info').click()
     } catch(e) {
       console.log('Retrying in 2 seconds...') //error handling
       checa();
     }
   }, 2000)
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Clique aqui para adicionar o botão
    
10.12.2018 / 15:14