何时使用递归函数?

Jay*_*Jay 3 javascript recursion function

我正在读关于递归函数我读到当我们使用递归函数时它调用一个堆栈帧,所以如果我们最终调用递归函数10000次,那么它可能是可用内存的问题.我有一个函数下面是否正确使用递归?或者你认为我应该避免它?

function animateLeft(obj, top){
   if(top >= 300){         
       obj.style.visibility = 'visible';
       return;  
   }
   else {
       var box = obj;
       box.style.marginLeft = top + "px";
       box.style.marginTop = top + "px";
       setTimeout(function(){
           animateLeft(obj, top + 1);
       }, 25) 
   }
}
function animateMe() {
    animateLeft(document.getElementById('inner-rectange'), 0);
}
Run Code Online (Sandbox Code Playgroud)

Col*_*inE 5

使用setTimeout意味着您的代码不会直接递归调用动画函数.这将导致重复调用该函数,但不会导致深层堆栈的创建.

对于动画来说,这是一种非常合理的方法(有更好的方法,例如requestAnimationFrame,但这是合理的!)