I am reading about recursive function I read that when we use recursive function it calls a stack frame so if we end up calling the recursive function 10000 times it might be an issue with available memory. I have a function below is it right to use recursion? or you think I should have avoided it?
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);
}
The use of setTimeout means that your code is not recursively calling the animation function directly. This will cause the function to be repeatedly invoked, but will not cause the creation of deep stack.
For an animation this is quite a reasonable approach (there are better approaches, such as requestAnimationFrame, but it is reasonable!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With