How to use jQuery setTimeout function
setTimeout function can be used for reloading page, show/hide jQuery UI Datepicker and for making a div disappear or appear after few seconds.
Related Post:
- Common jQuery Mistakes
- Latest jQuery interview questions and answers
- All kind of Client Side Validation using jQuery
The Basic syntax for setTimeout function is,
setTimeout(function() { // Do something after 2 seconds }, 2000);
The setTimeout function takes the times in miliseconds. And the block can contain either your jQuery code, or you can also make a call to any function.
For example, if I want to make div element fade out then you can use below code. It will fade out the div with id "dvData" after 2 seconds.
$(document).ready(function(){ setTimeout(function(){ $('#dvData').fadeOut();}, 2000); });
The above code will fade out the div after 2 seconds automatically when page is loaded.
You can also call this on button click as well. All you need to do is to put the above code on click of button.
$(document).ready(function() { $("#btnFade").bind("click",function() { setTimeout(function() { $('#dvData').fadeOut();}, 2000); }); });
You can also use below alternative that is create a function and call it on click of button.
$(document).ready(function() { $('#btnFade').bind('click', function() { FadeOut(); }); function FadeOut() { setTimeout(function() { $('#dvData').fadeOut();}, 2000); } });
As I mentioned earlier that with setTimeout(), you can also make a call to another function. Till now, we were writing a piece of code and that is ideal if your code is one line but when lines of code is more then it is better to create a separate function and call it in setTimeout().
$(document).ready(function() { $('#btnFade').bind('click', function() { FadeOut(); }); function FadeOut() { setTimeout(function () { FadeDiv(); }, 2000); } function FadeDiv() { $('#dvData').fadeOut(); } });
Feel free to contact me for any help related to jQuery, I will gladly help you.