Ian Vink
Ian Vink

Reputation: 68750

jquery - Timer?

I need to call my function abc(), 5 seconds after the document ready fires.

Is this possible in jQuery?

$(document).ready(function () {

//Wait 5 seconds then call abc();

});

function abc() {}

Upvotes: 6

Views: 13223

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49198

$(document).ready(function () {

    setTimeout(abc, 5000);

});

function abc() {}

Upvotes: 4

Use setTimeout("abc();", 5000); in your ready function.

Example (Don't use this, see below)

$(document).ready(function () {
  //Wait 5 seconds then call abc();
  setTimeout("abc();", 5000);
});

function abc() {}

The 5000 tells it to wait 5000 milliseconds which is 5 seconds. This is a basic JavaScript function and doesn't require jQuery (other than of course, the ready state event code). You can also use setInterval() if you want something to happen a recurring amount of times.

Edit: You can read more about it here(link removed).
Edit3: While my answer was not incorrect, it was not the best way to do it (as brought to my attention by david in the comment below.) A better way of doing it would be to pass the function abc itself directly into the setTimeout function. Like so:

$(document).ready(function () {
  //Wait 5 seconds then call abc();
  setTimeout(abc, 5000);
});

function abc() {}

This is better form because you're not passing the string argument which is eval'd and could cause security risks.

Also, a better link for documentation is here.

Upvotes: 8

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

$(document).ready(function () {

//Wait 5 seconds then call abc();
    setTimeout(abc, 5000);

});

setTimeout()link

Upvotes: 16

Related Questions