我正在编写一个小 jQuery 组件,它可以响应按钮按下而产生动画,并且也应该自动运行。我只是想知道这个函数是否递归,我无法弄清楚。
function animate_next_internal() {
$('#sc_thumbnails').animate(
{ top: '-=106' },
500,
function() {
animate_next_internal();
}
);
}
我的实际功能更复杂,允许停止和启动,这只是一个简化的示例。
编辑它可能会溢出堆栈,也可能不会溢出,具体取决于内部处理事件的方式。可能性:
animate() 直接调用done回调,这种情况下溢出是不可避免的。
animate() 通过某种外部调度机制调度回调,然后终止,在这种情况下它永远不会溢出。
最佳答案
我最初怀疑它会溢出内存,但我写了一个简短的测试来确认
function test(){
$(".logo img").css("position", "absolute");
$(".logo img").css("top", "100px");
$(".logo img").animate({top:0}, 500, function(){
test();
console.log("exits here");
});
}
test();
令人惊讶的是,我看到了
exits here
exits here
exits here
exits here
exits here
...
在我的日志中。看起来“animate() 通过某种外部调度机制安排回调进行调用,然后终止,在这种情况下它永远不会溢出。” 是正确的答案
关于jquery - 如果 jQuery 函数在其完成回调中调用自身,这会对堆栈造成递归危险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705345/