gpt4 book ai didi

javascript - Javascript 如何管理递归调用?

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:19 24 4
gpt4 key购买 nike

我正在闲逛 JavaScript,注意到一个奇怪的行为(至少对我来说很奇怪......)

所以我做了一个 SSCCE在这里:

我有一个名为“myDiv”的 div

function changeText(text){
document.getElementById("myDiv").innerHTML=text;
}

function recursiveCall(counter){
if(counter){
setTimeout(function(){
recursiveCall(--counter);
changeText(counter);
},750);
}
}

recursiveCall(10);

实例:http://jsfiddle.net/T645X/

所以我正在更改 div 上的文本,结果是文本从 9 变为 0,而我认为它应该从 0 变为 9,因为递归 changeText(counter ); 调用在调用实际更改文本的方法之前。

最佳答案

该函数包含一个异步超时。

setTimeout(function(){
recursiveCall(--counter);// calls the next function, which will call the next
// and print in a timeout
changeText(counter); // print
},750);

在递归调用超时之前更改了文本。

如果您愿意,可以将打印调用从超时时间之外移出,这将导致预期的行为:

function recursiveCall(counter){
if(counter){
recursiveCall(--counter);
setTimeout(function(){
changeText(counter);
},750);
}
}

(不过,请注意,这里的打印并没有分开计时,而且我们在某种程度上依赖于未定义的行为,假设它会先打印,只是因为我们把计时器放在第一位)

如果您希望它仍然延迟打印,您可以告诉函数它已完成。递归最初仍然会完成,但每个级别都会告诉它上面的级别它已完成:

function recursiveCall(counter,done){
if(counter){
// note how recursion is done before the timeouts
recursiveCall(counter-1,function(){ //note the function
setTimeout(function(){ //When I'm done, change the text and let the
changeText(counter-1); //next one know it's its turn.
done(); // notify the next in line.
},750);
});
}else{
done(); //If I'm the end condition, start working.
}
}

Here is a fiddle implementing this .

关于javascript - Javascript 如何管理递归调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17892195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com