问题描述
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
一个额外的问题,如果我安排了一些没有延迟的事情(基于数学而不是文字)会发生什么.是就地执行还是立即异步执行,还是定义了实现
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
这篇关于这是递归还是不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!