DeathByTensors
DeathByTensors

Reputation: 941

Run JavaScript function at regular time interval

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!

Upvotes: 38

Views: 56138

Answers (4)

Pradeep Kumar Das
Pradeep Kumar Das

Reputation: 891

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);

Upvotes: 1

Andrew Magee
Andrew Magee

Reputation: 6684

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

Upvotes: 19

rexcfnghk
rexcfnghk

Reputation: 15432

You can use window.setInterval

Sample usage:

window.setInterval(function () {
    console.log("foo");
}, 3000);

Upvotes: 4

Ry-
Ry-

Reputation: 224856

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.

Upvotes: 62

Related Questions