14

In my jquery function I have a loader gif image. After I show it I want to put a delay for a second and then continue to execute the rest of the code. How can I do that?

    $('#loader').css('display', '');

    //// I want to put here a delay. 

    var myDate = new Date();
    myDate.setFullYear(2013,8,2);

    var checkyear = myDate.getFullYear();
    var monthly =myDate.getMonth();
    var daily =myDate.getDate();

    $('#day').html(daily) ;
    $('#month').html(months[monthly]) ;
    $('#year').html(checkyear) ;
GG.
  • 21,083
  • 14
  • 84
  • 130
user1077300
  • 423
  • 4
  • 10
  • 18

5 Answers5

34

Set a timeout like this :

var delay = 1000;
setTimeout(function() {
 // your code
}, delay);

Example http://jsfiddle.net/HuLTs/

Paul Rad
  • 4,820
  • 1
  • 22
  • 23
7

Have you tried .delay ?

$('#loader').show(1).delay(1000).hide(1);

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Demo : http://jsfiddle.net/SBrWa/

GG.
  • 21,083
  • 14
  • 84
  • 130
  • 2
    `$('#loader').show().delay(1000).hide(0);` would be enough ;) +1 for showing alternative. Just as an inside, DOC concerning delay() seems no more to be accurate. Looks like a delay() can be canceled using jq 1.9 method .finish() – A. Wolff Sep 26 '13 at 11:42
6
$(document).ready(function(){ 
    setTimeout(function(){ 
      //your code
     },
  2000); 
});

Here 2000 refers to 2 seconds

coder
  • 13,002
  • 31
  • 112
  • 214
0

You can use this code,

$('#loader').css('display', '');

setTimeout(function() {
    var myDate = new Date();
    myDate.setFullYear(2013,8,2);

    var checkyear = myDate.getFullYear();
    var monthly =myDate.getMonth();
    var daily =myDate.getDate();

    $('#day').html(daily) ;
    $('#month').html(months[monthly]) ;
    $('#year').html(checkyear) ;
}, 1000);
zahirdhada
  • 405
  • 4
  • 14
0

Try this,

$(function(){
    $('#loader').css('display', '');
    setTimeout(function(){ 
        var myDate = new Date();
        myDate.setFullYear(2013,8,2);
        var checkyear = myDate.getFullYear();
        var monthly =myDate.getMonth();
        var daily =myDate.getDate();
        $('#day').html(daily) ;
        $('#month').html(months[monthly]) ;
        $('#year').html(checkyear) ;
    },1000);// 1 second delay
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106