Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make a jQuery function call after "X" seconds?
To make a jQuery function call after "X" seconds, use the setTimeout() method. This method allows you to delay the execution of any function by a specified number of milliseconds.
On button click, you can set a timeout and fade out an element. The setTimeout() method takes two parameters: the function to execute and the delay in milliseconds −
$("#button1").bind("click",function() {
setTimeout(function() {
$('#list').fadeOut();
}, 4000);
});
In the above code, 4000 represents 4000 milliseconds (4 seconds), which is the delay that occurs before fading out the element.
Example
You can try to run the following code to learn how to work with setTimeout() method in jQuery −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").bind("click",function() {
setTimeout(function() {
$('#list').fadeOut();
}, 4000);
});
});
</script>
</head>
<body>
<input type="button" id="button1" value="Fade Out" />
<br/>
<br/>
<div id="list">
<ul>
<li>India</li>
<li>US</li>
<li>UK</li>
</ul>
</div>
<p>The above data will fade out after 4 seconds</p>
</body>
</html>
When you click the "Fade Out" button, the list will disappear after 4 seconds. You can adjust the delay by changing the millisecond value in the setTimeout() function.
