How to use jQuery setTimeout function

The Basic syntax for setTimeout function is,

1 setTimeout(function() {
2       // Do something after 2 seconds
3 }, 2000);

The setTimeout function takes the times in miliseconds. And the block can contain either yourjQuery 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(){
2     setTimeout(function(){
3         $('#dvData').fadeOut();}, 2000);
4 });

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);
5   });
6 });

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() {
03       FadeOut();
04   });
05   function FadeOut()
06   {
07      setTimeout(function() {
08         $('#dvData').fadeOut();}, 2000);
09   }
10 });

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() {
03       FadeOut();
04   });
05     
06   function FadeOut()
07   {
08       setTimeout(function () { FadeDiv(); }, 2000);
09   }
10     
11   function FadeDiv()
12   {
13     $('#dvData').fadeOut();
14   }
15 });