37

I am currently building a website to host software. What I want is to add to the project pages is a slideshow of screenshots cycling, changing images about every 5 seconds. Is there any way to a script triggered at a time interval using just JavaScript? ..or will I have to resort to alternative methods for achieving my desired functionality. Thanks in advance for any help!

DeathByTensors
  • 901
  • 1
  • 10
  • 16
  • 2
    possible duplicate of [set Interval and Clear Interval](http://stackoverflow.com/questions/5978519/set-interval-and-clear-interval) – g.d.d.c Aug 06 '13 at 02:03

4 Answers4

62

setInterval:

function doSomething() {
    alert('This pops up every 5 seconds and is annoying!');
}

setInterval(doSomething, 5000); // Time in milliseconds

Pass it the function you want called repeatedly every n milliseconds. (setTimeout, by the way, will call a function with a timeout.)

If you ever want to stop the timer, hold onto setInterval’s return value and pass it to clearInterval.

Ry-
  • 218,210
  • 55
  • 464
  • 476
19

You want the setInterval function.

setInterval(function() {
  // This will be executed every 5 seconds
}, 5000); // 5000 milliseconds

Basic reference: http://www.w3schools.com/jsref/met_win_setinterval.asp (please ignore the reference to the "lang" parameter)

More indepth reference: https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval

Andrew Magee
  • 6,506
  • 4
  • 35
  • 58
  • Yeah, this is true. I'll replace with a better one. – Andrew Magee Aug 06 '13 at 02:06
  • 1
    W3schools may not be the most accurate but it's easier on mind and eyes. Beside who is just discovering about setinterval would greatly benefit from not seeing c code, getting to try it in browser, and get a organize reference. – Muhammad Umer Aug 06 '13 at 04:24
  • Ok fine I have both now :P – Andrew Magee Aug 06 '13 at 04:32
  • 1
    So just because something is not accurate but easy to read makes it a good resource? That's like walking into a classroom expecting to be taught physics but learning how to bake bread and being satisfied with the outcome – Joe Buckle Aug 06 '13 at 06:05
  • sure its not as definitive at places and misleading, but saying everything there is wrong is a BIG assumption. For basic stuff is more than enough. Also as i said, best stepping stone for someone just learning. When in doubt go to MDN. – Muhammad Umer Aug 06 '13 at 22:53
  • 1
    @MuhammadUmer: As you said, it’s misleading, and I’d say that “almost right” is a terrible stepping stone. Time to find the Meta question! – Ry- Aug 06 '13 at 23:52
4

You can use window.setInterval

Sample usage:

window.setInterval(function () {
    console.log("foo");
}, 3000);
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
1

It Changes the date time in a div and time changes frequently after 1 sec.

    setInterval(function(){
      var date=new Date();
      $('.class').html(date);
    },1000);