Delay, Sleep, Pause, Wait for 'X' Seconds | jQuery

The jQuery .delay() method provides a means to introduce a delay in the execution of subsequent functions within the queue. This delay can be applied to both the standard effects queue and custom queues, enabling precise control over the timing of function execution. This functionality proves valuable in scenarios where timed synchronization or animation sequencing is essential.

$(selector).delay(speed,queueName)
example
$("#delayDiv").delay(2000).fadeIn();

When this statement is executed, the element pauses for 2000 milliseconds before fading in.

run this source code Browser View



Full Source | jQuery
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#delayDiv").delay(2000).fadeIn(); }); }); </script> </head> <body> <button>Click me</button><br> <br> <div id="delayDiv" style="width:100px;height:100px;display:none;background-color:red;"></div><br> </body> </html>

jQuery delay() not working


How to wait 5 seconds with jQuery?

The jQuery .delay() method is specifically designed for delaying queued effects within the animation system and doesn't provide the flexibility of JavaScript's setTimeout() function for general-purpose delay. Thank you for pointing out this distinction and clarifying its limitations according to the jQuery documentation. For non-animation-related delays and more control over timing, using setTimeout() is indeed the recommended approach.

JavaScript setTimeout()

The first and the most common method in implementing a delay in the execution of a JavaScript code is to use the setTimeOut() method.

setTimeout(function, milliseconds, param1, param2, ...)
example
setTimeout( function() { //do something special }, 5000);
run this source code Browser View

Full Source | jQuery
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function demo1() { var delay = 2000; //4 second document.getElementById("board").innerHTML = "Waiting for 2 seconds...<br>"; setTimeout(function() { document.getElementById("board").innerHTML = document.getElementById("board").innerHTML + "code to be executed after 2 second..." }, delay); } </script> </head> <body> <input type="button" onclick="demo1()" value="Click here to Run Timer" /> <p id="board"></p> </body> </html>

Conclusion

The jQuery .delay() method facilitates timed delays within animation queues, ensuring the execution of subsequent effects at a specified interval. It's crucial to note that .delay() is intended for animation-related scenarios and may not provide the same versatility as JavaScript's setTimeout() function, which is better suited for broader timing requirements.