user558134
user558134

Reputation: 1129

jQuery clearTimeout on ajax success is getting confused and not clearing previous timeouts

I have a form submitted by jQuery ajax which has error validation server side. On beforeSend I show a gif loader and some loading text and when validation is send back on success method I show the appropriate messages for error. This messages have timeout to hide after x seconds. Anyways when i continue clicking the submit button, setTimeout is confusing itself and previous ones are not clearing. Here is the code I am using:

EDIT

$('form').on('submit', function(e) {

e.preventDefault();
var timer = null;

$.ajax({
    beforeSend; function() {
        $('.response').html('Processing form, please wait...');
    },

    success: function(data) {

        if(data.error == true) {
            $('.response').html('An error occurred.');
        } else {
            $('.response').html('Thank you. Form submitted successfully.');
        }

        if(timer) { clearTimeout(timer) };
        timer = setTimeout(function() {
            $('.response').html('* Indicates required fields.');
        }, 10000); 

    }
});
});

Any suggestions appreciated.

Upvotes: 0

Views: 1868

Answers (1)

Alexis King
Alexis King

Reputation: 43852

The timer variable is scoped to your success function, so it's always null when your code to clear the old timeout is reached. Move the declaration of timer outside your AJAX call, and it should work.

var timer = null;

$.ajax({
    beforeSend: function() { ... },
    success: function(data) {
        if(timer) { clearTimeout(timer) };
        timer = setTimeout(myfunction, 10000); 
    }
});

Upvotes: 2

Related Questions