避免“太多递归"错误 [英] Avoiding 'too much recursion' error

查看:48
本文介绍了避免“太多递归"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想做的事情归结为

Basically what I'm trying to do boils down to

function a() {
    // Do stuff that waits for things etc
    b(a);
}

function b(f) {
    f()
}

函数 a() { b(a);};函数 b(f) { f();};一种()不过,这会在一段时间后导致过多的递归错误.显然 javascript 不支持尾递归,因此也不起作用.我也想不出任何在这里使用循环的方法,因为我不想立即执行代码.那么有什么办法可以做到这一点还是不可能?

function a() { b(a); }; function b(f) { f(); }; a() That will cause a too much recursion error after a while though. Apparently javascript doesn't support tail-recursion so that won't work either. I can't think of any way to use a loop here either since I don't want the code executed immediately. So any way to do this or is it impossible?

如果之前有人问过这个问题,我也很抱歉,找不到任何有用的东西.

Also I apologize if this has been asked before, couldn't find anything that helped.

同样在任何人问之前,不,我实际上并没有使用 setTimeout 所以 setIntervall 不是一个选项.

Also before anyone asks, no I'm not actually using setTimeout so setIntervall isn't an option.

再次好的,希望这表明我正在努力做得更好.我需要在等待事情再次完成后调用相同的代码,而不是将其放入循环中并阻塞程序.

Edit again: Alright hope this shows what I'm trying to do better. I need to call the same code after waiting for things to complete again without actually putting it in a loop and blocking the program.

推荐答案

因为对 a() 的每次调用都会在下一次调用之前返回,所以不会进行递归.运行时系统反复对函数进行单独调用,并且在任何给定时间都不会有多个调用.

Because each call to a() returns before the next invocation, there is no recursion going on. The runtime system repeatedly makes individual calls to the function, and there won't ever be more than one call going on at any given time.

分解:

  • 在某处,您的代码调用 a() 开始循环
  • a() 的调用做事",然后调用 setTimeout()
  • 系统安排超时,该调用立即返回
  • a() 的原始调用完成
  • 100 毫秒后,计时器触发,运行时调用 a()
  • Somewhere, your code calls a() to start the cycle
  • That call to a() "does stuff" and then invokes setTimeout()
  • The system arranges for the timeout, and that call returns immediately
  • The original call to a() completes
  • 100 milliseconds later, the timer fires and the runtime invokes a()

此后循环重复.

edit 也许我应该更明确:递归这个词指的是一个函数直接或间接调用自身(同步)的过程.喜欢:

edit Maybe I should be more explicit: the word recursion refers to a process wherein a function invokes itself (synchronously) either directly or indirectly. Like:

function fibonacci(n) {
  return fibonacci(n - 1) + fibonacci(n - 2);
}

我们在 OP 中发布的代码中的内容完全不同.在该函数中没有对 a() 的调用(除非 OP 遗漏了一些重要的细节).相反,该函数的引用被移交给系统.直到原始调用完成后很长很长一段时间才会通过该引用进行调用.

What we have in the code posted in the OP is quite different. There's no call to a() being made from within that function (unless the OP left out some important details). Instead, a reference to the function is being handed over to the system. The call via that reference won't take place until a long, long time after the original call has finished.

这篇关于避免“太多递归"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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