让递归函数永远运行? [英] Leaving recursive functions running forever?

查看:54
本文介绍了让递归函数永远运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到一个函数,里面有一个 setTimeout ,超时时间呈指数增长(timeout * = 2).

I came across a function where it had a setTimeout inside with a timeout growing exponentially (timeout *= 2).

let timeout = 10000
function foo() {
    // doSomething without breaking, returning
    setTimeout(foo, timeout)
    timeout *= 2;
}
foo()

这似乎不应该是一个问题,并且直观地感觉到 setInterval 有点已经在做(具有无限循环,直到有可能被取消为止),我的问题在于方法本身.

It seems that this should not be a problem and intuitively feels like setInterval is kinda doing the same already (having an infinite loop until it's cancelled if ever), however, my question is in the approach itself.

  • 这是否可能导致内存泄漏?
  • 仍然限制该函数的调用次数更好/更清晰吗?
  • 其他语言会使用这种方法吗?或者在JS世界之外还有其他不同的心态?

推荐答案

这不是递归函数调用.调用 setTimeout 会导致 foo 在以后的JavaScript事件循环中被调用.

This is not a recursive function call. The call to setTimeout will cause foo to be called by the JavaScript event loop at a later time.

此代码不会导致堆栈溢出或任何此类问题.它应该是完全安全的.

This code will not cause a stack overflow or any such problems. It should be completely safe.

要深入了解其工作原理,建议阅读JS事件循环和微任务.

To understand how this works in-depth, I suggest reading up on the JS event loop and microtasks.

这篇关于让递归函数永远运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆