Try-catch in loop causing error

Asked

Viewed 70 times

1

I have the following code, which tries to click a button after 60 seconds, and if it has not pressed, 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 he’s not getting into the catch() and is, after some loop runs, making the page lock and close. Can you help me? What is being done wrong?

1 answer

3


Do not use while for this, use a function. while is asynchronous with setTimeout and will generate a bottleneck of processes, causing the lock. Using a function you can do synchronized, only calling the setTimeout again after 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 of 2 seconds:

By clicking on body, will insert the button with the class .department-info and fire 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.