开发者

Call a Javascript function every 5 seconds continuously [duplicate]

开发者 https://www.devze.com 2023-03-31 04:23 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Calling a function every 60 seconds
This question already has answers here: Closed 11 years ago.

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 fi开发者_如何学Pythonne if I want it continuously?


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

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

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


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


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.


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消