jQuery setTimeout() Function [duplicate]

The problem is that inside the setTimeout() call, this doesn’t refer to the button. You need to set a variable to keep the reference to the button.

I’ve created a sample below. See how I use the variable named $this.

$(".submit_wide").click(function () {
    var $this = $(this);
    $this.val('Please wait..');
    $this.attr('disabled', true);
    setTimeout(function() { 
        $this.attr('disabled', false);
        $this.val('Submit');
    }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" class="submit_wide" value="Submit"/>

UPDATE: Now with modern browsers supporting Arrow Functions, you can use them to avoid altering the this context. See updated snippet below.

$(".submit_wide").click(function () {
    $(this).val('Please wait..');
    $(this).attr('disabled', true);
    setTimeout(() => { 
        $(this).attr('disabled', false);
        $(this).val('Submit');
    }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" class="submit_wide" value="Submit"/>

Leave a Comment

tech