In this post, we will learn how to call a function after waiting for some time in jQuery. When we want to get a response 10 seconds after clicking the button. So how we can do this, we will know in this post.


How To Call A Function After Waiting For Some Time In jQuery ?


Call A Function After Waiting For Some Time

To call a function after waiting for some time, we use the  delay()  jQuery method. This functions helps us to call a function after some time. With this method we use  queue()  method. This method shows the queue of functions to be executed. This method is used together with  dequeue()  method. This method removes the next function from the queue. 


We have used all these methods in the example given below. So let's check this example.


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Call A Function After Waiting For Some Time In jQuery ?</title>
<style>

/* Text hide */
h1 {
display: none;
}

</style>
</head>
<body>

<!-- This text will show after click on the button -->
<h1>CodexRadar</h1>

<button type="button">Click Me!</button>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>

// Function to show text
function showText() {
$("h1").fadeIn(1000);
}


$(document).ready(function() {
$("button").click(function() {

//this text show after click on button
$(this).text('loading...').delay(2000).queue(function() {

//When text show then hide the button
$(this).hide();

// call showText() function
showText();

//removes the function from the queue
$(this).dequeue();
});
});
});

</script>
</body>
</html> code-box



Summary

In this post we learned how to call a function after waiting for some time in jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post