Recursive setInterval() runs continuously

旧城冷巷雨未停 提交于 2019-12-19 17:35:20

问题


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

回答1:


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.




回答2:


You're calling five immediately, instead of merely passing it in:

function five () {
    console.log("five");
}
setInterval(five, 5000);
/*              ^     */



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/18687795/recursive-setinterval-runs-continuously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!