The Basic syntax for setTimeout function is,
1 |
setTimeout( function () { |
2 |
// Do something after 2 seconds |
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 (){ |
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(); |