Javascript:settimeout 递归无限堆栈增加? [英] Javascript: settimeout recursion endless stack increase?

查看:59
本文介绍了Javascript:settimeout 递归无限堆栈增加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是使用 HTML/CSS/JS 制作背景图片的幻灯片.我发现的许多解决方案都促进了这样的事情:

My goal is a slideshow of background images with HTML/CSS/JS. Many solutions that I've found promote something like this:

my_recursion();

function my_recursion () {
 // cycle the Background image ...
 setTimeout(my_recursion, 3000);
}

我认为这是不好的风格有错吗?我希望在例如循环 1000 my_recursion 的所有其他 999 个实例仍然打开/在堆栈上?这不是创建和消耗越来越多内存的无限堆栈吗?

Am I wrong to assume that this is bad style? I would expect that at e.g. cycle 1000 all the other 999 instances of my_recursion are still open / on the stack? Doesn't this create and infinite stack which consumes more and more memory?

或者是否涉及某种智能,例如如果一个函数在最后调用自身,则第 (n-1) 个函数将被销毁,包括在其中分配的所有变量"?

Or is there some sort of intelligence involved which does something like "if a function calls itself at the end, the (n-1)th function is destroyed including all variables that were assigned inside of it"?

推荐答案

这不会导致堆栈无限增加,因为 setTimeout 的工作方式,恕我直言,它的风格还不错.

This will not result in endless stack increase, because of the way setTimeout works, and imho it is not bad style.

setTimeout 不保证代码会在给定的超时后直接运行.相反,在超时之后,它会将回调推送到队列"上,当堆栈为空时将对其进行处理.所以它只会在 my_recursion 返回并且堆栈为空时运行.

setTimeout does not guarantee that code will run directly after the given timeout. Instead, after that timeout it will push the callback onto a "queue", which will be processed when the stack is empty. So it will only run when my_recursion has returned and the stack is empty.

如果一个函数在最后调用自己 (...)

If a function calls itself at the end (...)

my_recursion 不会在任何地方调用自己.它只是将自身作为参数传递给 setTimeout.之后,它会继续执行,之后直接返回,并从堆栈中弹出.

my_recursion doesn't call itself anywhere. It just passes itself as an argument to setTimeout. After that, it will just continue executing, return directly after, and will be popped from the stack.

本演示文稿解释了堆栈和事件队列.

这篇关于Javascript:settimeout 递归无限堆栈增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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