How to call a function automatically after waiting for some time using jQuery?
In order to run a function automatically after waiting for some time, we are using the jQuery delay() method.
The .delay() method in jQuery which is used to set a timer to delay the execution of the next item in the queue.
Syntax:
$(selector).delay(para1, para2);
Approach:
- When the Button is clicked the process is delayed to the specific time period using .delay() method.
- Functions or process is queued using .queue() method. After the process or functions are executed, all executed functions are dequeued using .dequeue() method.
Example 1:
html
<!DOCTYPE html> < html > < head > < title >How to call a function automatically after waiting for some time using jQuery</ title > < script src="https://code.jquery.com/jquery-1.12.4.min.js"> </ script > < style type="text/css"> img { display: none; } </ style > </ head > < body > < center > < h1 style="color:green;"> w3wiki </ h1 > < h3 >How to call a function automatically after waiting for some time using jQuery</ h3 > < button type="button" class="show-image">Click</ button > < img src= "https://media.w3wiki.net/wp-content/uploads/20190912174307/qwe1.png" /> < script type="text/javascript"> function showImg() { $("img").fadeIn(1500); } $(document).ready(function() { $(".show-image").click(function() { $(this).text('Wait...').delay(1000).queue(function() { $(this).hide(); showImg(); $(this).dequeue(); }); }); }); </ script > </ center > </ body > </ html > |
Output:
Example 2: Along with alert method
html
<!DOCTYPE html> < html > < head > < title >How to call a function automatically after waiting for some time using jQuerye</ title > < script src="https://code.jquery.com/jquery-1.12.4.min.js"> </ script > < style type="text/css"> img { display: none; } </ style > </ head > < body > < center > < h1 style="color:green;"> w3wiki </ h1 > < h3 >How to call a function automatically after waiting for some time using jQuery</ h3 > < button type="button" class="show-image"> Click </ button > < img src= "https://media.w3wiki.net/wp-content/uploads/20190912174307/qwe1.png" /> < script type="text/javascript"> function showImg() { $("img").fadeIn(1500); } $(document).ready(function() { $(".show-image").click(function() { $(this).text('Wait...').delay(1000).queue(function() { $(this).hide(); showImg(); $(this).dequeue(); alert("Waiting time is over"); }); }); }); </ script > </ center > </ body > </ html > |
Output: