递归setInterval()连续运行 [英] Recursive setInterval() runs continuously
问题描述
我正在尝试使用递归setInterval函数使用JavaScript每5秒运行一个函数.
I'm trying to run a function every 5 seconds using JavaScript using a recursive setInterval function.
下面的代码只是尽可能快地记录启动",然后使浏览器崩溃.为什么这不是每5秒运行一次?
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();
推荐答案
请勿以这种方式使用setInterval.使用setTimeout.通过调用setInterval,可以在每次调用该函数时创建一个UNIQUE计时器.SetTimeout将创建一个结束的计时器,然后创建一个新计时器.
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.
您还应该更改引用 5
的方式. five()
立即执行该功能.只是五个
传递了一个函数引用,因此,如下所示.
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.
这篇关于递归setInterval()连续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!