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.

Afnan Bashir
  • 7,349
  • 19
  • 74
  • 138
Elitmiar
  • 32,536
  • 72
  • 175
  • 228

8 Answers8

216

You can use this:

window.setInterval(yourfunction, 10000);

function yourfunction() { alert('test'); }
Pavel Chuchuva
  • 21,996
  • 9
  • 95
  • 113
Kristof Claes
  • 10,617
  • 3
  • 29
  • 41
50
window.setInterval(function() {
 alert('test');
}, 10000);

window.setInterval

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

rahul
  • 179,909
  • 49
  • 229
  • 260
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...
jchavannes
  • 2,150
  • 1
  • 24
  • 12
25

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

window.setInterval(function() {
    alert('test');
}, 10000);
Ikke
  • 95,379
  • 23
  • 93
  • 119
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.

Craig
  • 6,559
  • 3
  • 31
  • 48
3

try jQueryTimers, they have great functionality for polling

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

Dave Jarvis
  • 29,586
  • 38
  • 176
  • 304
Eggie
  • 127
  • 10
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();
Sid
  • 4,772
  • 14
  • 57
  • 107
Aren Hovsepyan
  • 1,837
  • 2
  • 14
  • 39
-2
function run() {
    window.setTimeout(
         "run()",
         1000
    );
}
harpax
  • 5,834
  • 5
  • 34
  • 49
  • 6
    -1, because providing a string to eval instead of simply providing the function is the root of too many bugs. – vog Dec 21 '10 at 14:18