Search code examples
jquerydelay

Need a delay in a jQuery function


I need to put a one second delay in this jQuery function so that when the captcha is filled in correctly, there is a sufficient delay (one second, I think) for the #captchaStatus to show before the next step of the process (which is a html being posted).

Must be fairly easy, though I'm learning jQuery.... Ideas? Thanks.

function validateCaptcha()
{
    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    //alert(challengeField);
    //alert(responseField);
    //return false;
    var html = $.ajax({
    type: "POST",
    url: "/wp-content/themes/default/ajax.recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
    async: false
    }).responseText;

    if(html == "success")
    {
        $("#captchaStatus").html("You got it right - I'm sending the email now....");
        return true;
    }
    else
    {
        $("#captchaStatus").html("Your captcha is incorrect - please try again...");
        Recaptcha.reload();
        return false;
    }
}

Solution

  • You should be using a callback. check out this jQuery FAQ item on this.

    The code does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined.

     getUrlStatus('getStatus.php', function(status) {
        alert(status);
     });
    
    
    function getUrlStatus(url, callback) {
      $.ajax({
         url: url,
         complete: function(xhr) {
             callback(xhr.status);
         }
      });
    }