0

I'm using Google's reCAPTCHA on a form and after every submit I need it reset, because if the server-side validation fails and the user resubmits the same form, the captcha will be invalid. I'm using plain javascript, not using ajax/jquery, the form opens a new page (instead of reloading the current one). Here's my code:

document.getElementById('myform').addEventListener('submit', function(event) {
    event.preventDefault();
    this.submit();
    setTimeout(function(){ grecaptcha.reset(myCaptcha); }, 0);
}

I'm using setTimeout to put the reset code in the event loop queue.

My question is, will this work every time? Is submit() synchronous, i.e. it will always execute before whatever is in the event loop queue?

Martin
  • 111
  • 1
  • 10

1 Answers1

2

Yes! See here:

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

So this.submit() will run to completion before setTime() begins executing.

Community
  • 1
  • 1
Nick Bull
  • 9,518
  • 6
  • 36
  • 58