637

JQuery, how to call a function every 5 seconds.

I'm looking for a way to automate the changing of images in a slideshow.

I'd rather not install any other 3rd party plugins if possible.

Community
  • 1
  • 1
ensnare
  • 40,069
  • 64
  • 158
  • 224
  • 143
    +1 for "I'd rather not install any 3rd party plugins if possible." – nickf Jan 31 '10 at 07:55
  • 12
    @nickf: Because it's humorous as jQuery is already 3rd-party? (But not really, because I'm sure he's using jQuery for other stuff already) – mpen Jan 31 '10 at 08:22
  • 34
    @Mark, hehe no I wasn't being sarcastic, it's just that I see a lot of people jump straight to plugins even though their problem could be solved with a couple of lines of plain javascript. – nickf Jan 31 '10 at 13:11
  • 9
    A couple of lines of quirky hacks and you never know in which browsers it will work. – Gherman Sep 19 '14 at 06:17
  • 11
    Note that for those looking to use this technique in combination with an AJAX request - ***DON'T DO IT THIS WAY***. Having every user on your page call your server every N seconds is equivalent of DDOSing yourself. If you need to keep the server and UI in sync, use WebSockets instead. – Rory McCrossan Jun 30 '17 at 07:51
  • 1
    Just to expand on the comment of @RoryMcCrossan, if you have to use intervals (because technical reasons maybe), make your program so that a connection failure increases the delay between reconnect attempts, instead of decreasing like some [netgear routers](http://pages.cs.wisc.edu/~plonka/netgear-sntp/) did in the past – Ferrybig Aug 25 '17 at 06:20

7 Answers7

1124

You don't need jquery for this, in plain javascript, the following will work:

var intervalId = window.setInterval(function(){
  // call your function here
}, 5000);

To stop the loop you can use:

clearInterval(intervalId) 
ecraig12345
  • 2,328
  • 1
  • 19
  • 26
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
137

you could register an interval on the page using setInterval, ie:

setInterval(function(){ 
    //code goes here that will be run every 5 seconds.    
}, 5000);
John Boker
  • 82,559
  • 17
  • 97
  • 130
  • 2
    yeah i fixed it, trying to type too fast, knew it would be answered quickly :) – John Boker Jan 31 '10 at 07:35
  • Your opening suggestion still references setTimeout :) – Sampson Jan 31 '10 at 07:35
  • 1
    well, thanks :) man it's late. need to stop trying to answer questions when tired. – John Boker Jan 31 '10 at 07:48
  • 1
    You could always call `setTimeout` again from within the function....that's the way I used to do it >.< I guess it can't be an anonymous function then. Unless there's some sort of call_self() function I'm unaware of. – mpen Jan 31 '10 at 08:24
  • @Mark Yup, that's how I do it when timing is not very critical, but a job needs to execute periodically. – HRJ Jan 31 '10 at 09:07
  • For those now in the world of ES6, this should be useful: setInterval(() => { alert("Meow i'm a cat"); }, 1000); – Oisín Foley Feb 15 '18 at 13:30
60

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function everyTime() {
    console.log('each 1 second...');
}

var myInterval = setInterval(everyTime, 1000);

call this line to stop the loop:

 clearInterval(myInterval);
Ricardo Figueiredo
  • 1,416
  • 13
  • 10
50

Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:

my_function(){};
setInterval(my_function,10000);
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
  • 7
    If you do not call it once, the first call will be in 10000ms. If you want one right away, you can still call it normally once. – jeromej Sep 08 '15 at 09:21
  • This answer has saved me a LOT of time; I would've been wondering why my function wasn't being called for ages. Lucky I stumbled across this answer; +1 – Often Right Jul 12 '16 at 08:50
38

The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}
Steel Brain
  • 4,321
  • 28
  • 38
14

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suits you most and how to stop each of them.

Dror
  • 7,255
  • 3
  • 38
  • 44
7

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>
erdeepak
  • 385
  • 1
  • 5
  • 14