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

jQuery delay() method allow you to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue.
$(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?
jQuery delay() will not do the job. The problem with delay() is it's part of the animation system, and only applies to animation queues. As per jQuery Documentation: The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

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>