Search code examples
javascriptsetintervalinvisible-recaptcha

How can i set interval not on the first load but second load and load after that


I am using setInterval for my recaptcha javascript code because most of my forms are very long and the token will expire leaving the user to refill the form all over again.

And i like how the code is now EXCEPT it takes also 10 seconds for the token to load. I also have 1 input for the user to fill in and that can be submitted within 10 seconds then it will give a recaptcha error.

How can i let the code below load the first time without setInterval and EVERY time after the first time to be with 10 seconds interval?

Thanks for your time.

  setInterval(function(){
  grecaptcha.ready(function() {
      grecaptcha.execute('<?php echo RECAPTCHA_SITE_KEY; ?>', {action: 'this_form'}).then(function(token) {
        $('#token').val(token);
        $('#action').val('this_form');
      });
  });
}, 10000);

Solution

  • How can i let the code below load the first time without setInterval and EVERY time after the first time to be with 10 seconds interval?

    You can use setTimeout for this. Give it a try:

    
    function loadCaptcha() {
      grecaptcha.ready(function() {
          grecaptcha.execute('<?php echo RECAPTCHA_SITE_KEY; ?>', {action: 'this_form'}).then(function(token) {
            $('#token').val(token);
            $('#action').val('this_form');
          });
      });
    }
    
    $(document).ready(function() {
      loadCaptcha();
      setTimeout(function() {
        loadCaptcha();
        setInterval(loadCaptcha, 10 * 1000); // fire every 10 sec
      }, 10 * 1000); // fire only one time after 10 sec
    });