为什么 setTimeout 调用的函数没有调用栈限制? [英] Why the function called by setTimeout has no callstack limit?

查看:24
本文介绍了为什么 setTimeout 调用的函数没有调用栈限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

超过最大调用堆栈大小

调试的时候发现变量作用域不包括之前执行的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 will never overflow the stack.

这不是递归调用,对于哪个范围(在非tail-call-优化函数)需要保留.但这也意味着函数会阻塞,这不是您想要的.

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屋!

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