这是递归还是没有 [英] Is this recursion or not

查看:136
本文介绍了这是递归还是没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function x(){
  window.setTimeout(function(){
     foo();
     if(notDone()){ 
        x();
     };
  },1000);
}

我担心无限制的堆栈增长。我认为这不是递归,因为定时器中的x()调用会根据JS引擎中的新调度生成一组全新的堆栈帧。

My concern being unbounded stack growth. I think this is not recursion since the x() call in the timer results in a brand new set of stack frames based on a new dispatch in the JS engine.

但是阅读代码作为一个老式的非JS家伙让我感到不安

But reading the code as an old-fashioned non JS guy it makes me feel uneasy

一个额外的问题,如果我安排了什么会发生什么(基于数学而不是文字)没有延误。会执行到位还是会立即执行async,或者是实现定义

One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined

推荐答案

从某种意义上说这是隐实的它是一个调用自身的函数,但我相信你对堆栈跟踪的消失是正确的。在正常执行下,堆栈将只显示它是由setTimeout调用的。例如,chrome调试器将允许您保持堆栈跟踪在异步执行时,我不确定他们是如何做的,但引擎可以以某种方式跟踪堆栈。

It is recusive in a sense that it is a function that calls itself but I believe you are right about the stack trace being gone. Under normal execution the stack will just show that it was invoked by setTimeout. The chrome debugger for example will allow you to keep stack traces on async execution, I am not sure how they are doing it but the engine can keep track of the stack somehow.

无论文字如何计算,执行仍然是异步。

No matter how the literal is calculated the execution will still be async.

setTimeout(function(){console.log('timeout');}, 0);console.log('executing');

将输出:

executing
undefined
timeout 

这篇关于这是递归还是没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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