Call a Javascript function every 5 seconds continuously

JavascriptDom Events

Javascript Problem Overview


> Possible Duplicate:
> https://stackoverflow.com/questions/3138756/jquery-repeat-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?

Javascript Solutions


Solution 1 - Javascript

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

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

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeepmoteriaView Question on Stackoverflow
Solution 1 - JavascriptAnantha SharmaView Answer on Stackoverflow
Solution 2 - JavascriptShefView Answer on Stackoverflow
Solution 3 - JavascriptJose FaetiView Answer on Stackoverflow
Solution 4 - Javascriptgion_13View Answer on Stackoverflow
Solution 5 - JavascriptIladarsdaView Answer on Stackoverflow