I'm trying to run a function every 5 seconds using JavaScript using a recursive setInterval function.
The following code just logs "started" as fast as possible and then crashes the browser. Why is this not running every 5 seconds?
function five() {
console.log("five");
setInterval(five(), 5000);
}
five();
Don't use setInterval this way. Use setTimeout. By calling setInterval, you create a UNIQUE timer every time the function is called. SetTimeout would create one timer that ends, and then creates a new timer.
You should also change the way you reference five
. five()
executes the function immediately. Just five
passes a function reference, so do it as you see below.
function five() {
console.log("five");
setTimeout(five, 5000);
}
five();
Of course, you can always pass the function call as a string to be evaluated:
setTimeout("five()", 5000); // note the quotes
But this is generally considered bad practice.
You're calling five
immediately, instead of merely passing it in:
function five () {
console.log("five");
}
setInterval(five, 5000);
/* ^ */
Change this line:
setInterval(five(), 5000);
like this:
setInterval(five, 5000);
But seems like what you really need is:
setTimeout(five, 5000);
So your code will look like:
function five() {
console.log("five");
setTimeout(five, 5000);
}
five();
The reason of crashing it is that you are calling the function five. Instead of that you should pass it as parameter.
setInterval(five, 5000);