为什么setTimeout调用的函数没有调用栈限制? [英] Why the function called by setTimeout has no callstack limit?
问题描述
timer = window.setTimeout(function () {
//do something
window.setTimeout(arguments.callee, 1000);
}, 1000);
结果是这些代码可以正常工作。
the result is that these codes work well.
但是为什么不是导致以下错误?
but why doesn't it cause the error below?
最大调用堆栈大小超出了
Maximum Call Stack Size Exceeded
调试时,发现变量范围不包括先前执行的 setTimeout函数的范围
when debugging it, find the variable scope don't include the scope of previous executed "setTimeout function"
谁可以解释这个问题?
最好提供文档。
推荐答案
setTimeout
是异步的(在执行回调之前返回),并且回调将在新的空堆栈帧上执行。这就是全部目的。
setTimeout
is asynchronous (it returns before executing the callback), and the callback will be executed on a new, empty stack frame. That's the whole purpose.
这不是递归调用,它的作用域(在非尾调用优化功能)需要保留。但这也意味着该函数被阻塞了,这不是您想要的。
It is not a recursive call, for which scope (in case of a non-tail-call-optimized function) would need to be retained. But that would also mean that the function became blocking, which is not what you want.
这篇关于为什么setTimeout调用的函数没有调用栈限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!