jQuery setTimeout() function

set-time-out

If we want to run a block of code after a specified time means we can use jQuery setTimeout() method. What it will do is, it will run specified code at specified millisecond. Syntax for this method is setTimeout(code,milliseconds).

jQuery(document).ready(function () {
    jQuery('.submit').click(function(){
        var T = setTimeout(showAlert, 3000);
    });
});

function showAlert(){
    alert("Its fired after 3 seconds");
}

Html code

<button id="submit">Submit</button>

In the above code, function showAlert() will be called after 3 seconds after clicking submit id.

We can clear the time which is set by setTimeout() by using this method clearTimeout(id).
It accepts one parameter which is returned by the setTimeout().
ie., We can stop the setTimeout() timer by passing its id ‘T’ to the clearTimeout() method like this clearTimeout(T).
‘T’ is the id, which is assigned to the setTimeout() method.

Click here for live demo

Note:
Don’t write ‘out’ in method like this setTimeOut() – Here ‘o’ is written in UPPERCASE, if we put ‘o’ in UPPERCASE it will not work.
I had this problem once:(

Leave a Reply