Search code examples
jquerytimeoutsettimeoutcleartimeout

clearTimeout not working with multiple functions


clearTimeout isn't working in my code. I defined the variable global so every function should have access to it. Here is my code for better understanding (see comments in code):

$(document).on('click', '#submit', function() { /* SECOND CLICK IS AFTER ~2 SECONDS */
    var timeout;

    validation();

    mysql();

    function validation() {
        if (condition) {
            if (timeout) {
                console.log('timeout set');
            } else {
                console.log('timeout not set'); /* GET THIS BUT TIMEOUT MADE CHANGE AFTER DEFINED TIME */

            clearTimeout(timeout);

            if (timeout) {
                console.log('timeout set');
            } else {
                console.log('timeout not set'); /* GET THIS */
            }
        }   
    }

    function mysql() {
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            dataType: 'json',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                timeout = setTimeout(function() {
                    $('.message').html('message for user');
                }, 7500);
            }
        })
    }
});

Solution

  • $(document).on('click', '#submit', function() { /* SECOND CLICK IS AFTER ~2 SECONDS */
        var timeout;
    

    The issue is your scope for timeout. It is scoped to the click event handler. So each time you perform this click logic, it creates a new instance for the context. If you want to share a single timeout variable for all clicks, it needs to be moved to a higher scope, outside of the event handler.

    For a more detailed question about variable scope in javascript, please reference: What is the scope of variables in JavaScript?