JavaScript 中的递归和 setTimeout
我的 JavaScript 文件中有一个递归函数。它看起来像这样:
function process(node){
if(someCondition)
return someValue;
a = process(node.children);
b = doSomething(a);
return b;
}
问题是我想在此递归的每一步中将系统状态显示到 HTML 输出。每个步骤之间应该有一个延迟。 (假设我想向用户实时显示递归)。在任何其他语言中,我都会在函数内部使用delay()调用,但是由于JavaScript除了setTimeout()之外不支持做这样的事情,所以我迷失了,因为我不知道如何在这个特定的情况下使用setTimeout调用案件。
通常在更简单的情况下,我会使用这样的东西:
function process(node){
if(someCondition)
return someValue;
setTimeout("process(node.children)", delay);
}
;但是由于我的原始函数返回一个值,我不知道如何继续。
提前致谢。
I have a recursive function in my JavaScript file. It looks something like this:
function process(node){
if(someCondition)
return someValue;
a = process(node.children);
b = doSomething(a);
return b;
}
The problem is that I want to display the state of the system to the HTML output on each step of this recursion. There should be a delay between each step. (Just assume that I want to display the recursion live to the users). In any other language I would use a delay() call inside the function, but since JavaScript supports nothing other than setTimeout() to do something like this, I am lost because I don't know how to use the setTimeout call in this particular case.
Normally in simpler cases I would use something like this:
function process(node){
if(someCondition)
return someValue;
setTimeout("process(node.children)", delay);
}
;but since my original function returns a value, I don't know how to proceed.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用“安全”递归,您可以轻松更新 dom,请参阅 https:// /stackoverflow.com/questions/24208676/how-to-use-recursion-in-javascript/24208677
You can easily update the dom if you use "safe" recursion, see https://stackoverflow.com/questions/24208676/how-to-use-recursion-in-javascript/24208677
那又怎样呢?
What about that?
如果您的目标是 HTML5,您可以尝试使用 Web Worker 。
You might try a web worker, if you're targeting HTML5.
例子:
Example:
我认为这不能作为纯粹的递归算法。
您可以将 b 的当前值存储在全局变量中。
然后,您可以使用 setInterval 以类似的方式处理该值,在每次迭代时更新 b 的值,并在满足条件时使用clearTimeout 停止执行。
I think this will not work as a pure recursive algorithm.
You could store the current value of b in a global variable.
You could then us setInterval to process the value in a similar way, updating the value of b on each iteration, using clearTimeout to stop execution when the condition is met.