How to use setTimeout function in jquery, make a delay in code execution.

jQuery setTimeout can be used if we need a delay in our code. It executes the code with a delay of specified time in milliseconds. Normally 1 second is equal to 1000 millisecond. This function accepts the first argument as a reference to a function.

Example:

function timeoutTrigger(){
  alert("Alert Fired!");
}
setTimeout(timeoutTrigger, 500);  // fires after a delay of 0.5 milliseconds

Sample syntax with 1 second delay.

setTimeout(function(){
    alert("Fired after one second"); 
}, 1000);

Sample Program:

$(document).ready(function() {
    console.log("Document ready");
    setTimeout(function(){
       // Have a look at the browser console to check the order of code execution
       console.log("Timeout executed"); // this block of code executes after the time delay 
    }, 2500);
    console.log("End of Document ready");
});

Output Console:

timeoutscreen.PNG

Category: