[javascript] Call a Javascript function every 5 seconds continuously

Possible Duplicate:
Calling a function every 60 seconds

I want to Call a Javascript function every 5 seconds continuously. I have seen the setTimeOut event. Will it be working fine if I want it continuously?

This question is related to javascript dom-events

The answer is


You can use setInterval(), the arguments are the same.

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

As best coding practices suggests, use setTimeout instead of setInterval.

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.


Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/

Plus:

  • has nice fade in / fade out animation
  • will pause on :hover
  • will prevent running multiple actions (finish run animation before starting second)
  • will prevent going broken when in the tab ( browser stops scripts in the tabs)

Tested and working!


Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);