If you want to delay your
jQuery code to run after some amount of time, you can use JavaScript
setTimeout function to delay the execution.
setTimeout is used in JavaScript to delay execution of some code and the same function can be use with
jQuery without any extra effort.
Related Post:
- Common jQuery Mistakes
- All kind of Client Side Validation using jQuery
The Basic syntax for setTimeout function is,
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.
1 | $(document).ready(function(){ |
3 | $('#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.
1 | $(document).ready(function() { |
2 | $("#btnFade").bind("click",function() { |
3 | setTimeout(function() { |
4 | $('#dvData').fadeOut();}, 2000); |
You can also use below alternative that is create a function and call it on click of button.
01 | $(document).ready(function() { |
02 | $('#btnFade').bind('click', function() { |
07 | setTimeout(function() { |
08 | $('#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().
01 | $(document).ready(function() { |
02 | $('#btnFade').bind('click', function() { |
08 | setTimeout(function () { FadeDiv(); }, 2000); |
13 | $('#dvData').fadeOut(); |