Thursday, February 9, 2012

How to use jQuery setTimeout function

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. Since jQuery is written on top of JavaScript, so you can use all JavaScript functions with jQuery as well. Read how to use JavaScript String Functions in jQuery.

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:

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.