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.

<!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

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);

<!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>
Related Topics
- How to get input textbox value using jQuery
- Get Selected Dropdown Value on Change Event | jQuery
- How to submit a form using ajax in jQuery
- How can I get the ID of an element using jQuery
- Open Bootstrap modal window on Button Click Using jQuery
- How to select an element with its name attribute | jQuery
- How to get the data-id attribute using jQuery
- How to disable/enable submit button after clicked | jQuery
- How to replace innerHTML of a div using jQuery
- Change the selected value of a drop-down list using jQuery
- How to get the value of a CheckBox with jQuery
- How to detect enter key press on keyboard | jQuery
- How to allow numbers only in a Text Box using jQuery.
- How to dynamically create a div in jQuery?