137

Is there anyway to implement a timer for JQuery, eg. every 10 seconds it needs to call a js function.

I tried the following

window.setTimeout(function() {
 alert('test');
}, 10000);

but this only executes once and then never again.

8 Answers 8

216

You can use this:

window.setInterval(yourfunction, 10000);

function yourfunction() { alert('test'); }
Sign up to request clarification or add additional context in comments.

Comments

50
window.setInterval(function() {
 alert('test');
}, 10000);

window.setInterval

Calls a function repeatedly, with a fixed time delay between each call to that function.

Comments

45

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

4 Comments

nice utility. Allows controlling lifecycle.
very useful for when one timer needs to control another timer
i m getting an error :( "TypeError: $.timer is not a function"
that is because you need to get the plugin from the link.
25

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

Comments

11

jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.

$('#foo').slideUp(300).delay(800).fadeIn(400);

http://api.jquery.com/delay/

Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.

Comments

3

try jQueryTimers, they have great functionality for polling

http://plugins.jquery.com/project/timers

1 Comment

Link in answer is dead.
2

You can use setInterval() method also you can call your setTimeout() from your custom function for example

function everyTenSec(){
  console.log("done");
  setTimeout(everyTenSec,10000);
}
everyTenSec();

Comments

-2
function run() {
    window.setTimeout(
         "run()",
         1000
    );
}

1 Comment

-1, because providing a string to eval instead of simply providing the function is the root of too many bugs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.