Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform an action every couple of seconds?

Tags:

javascript

Can someone quickly and simply explain to me how to perform an action every couple of seconds using

var timeOut = setTimeout(FunctionName, 5000);

I want to run a function every 5 seconds.

like image 931
Iladarsda Avatar asked Aug 02 '11 09:08

Iladarsda


People also ask

How do you call a function after every second?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

How do you call a function after every 5 seconds?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

How do you call a function repeatedly every 5 seconds in JavaScript?

The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.


3 Answers

As you asked for a method using setTimeout:

function doStuff() {
   console.log("hello!");
   setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);

But it would probably be better to use setInterval:

function doStuff() {
   console.log("hello!");
}
setInterval(doStuff, 5000);
like image 128
James Allardice Avatar answered Nov 14 '22 03:11

James Allardice


Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.

like image 44
miku Avatar answered Nov 14 '22 03:11

miku


Use setInterval:

var timeOut = setInterval(nextNotice, 5000);
like image 23
Igor Dymov Avatar answered Nov 14 '22 03:11

Igor Dymov