I'm trying to build a loop function with a delay. I've found this solution here:
How do I add a delay in a JavaScript loop?
...but because I want to use the function several times, I want to pass variables to the function. This is proving difficult. For example, say I've got a function called "animate_block" that I want to call with variable "blah". This function itself calls another function with this variable, then moves the variable forward by 1 until it reaches some limit, with a recursive setTimeout so it doesn't all happen at once. Should it look something like:
animate_block(blah)
function animate_block(ab_blah){
move_block(ab_blah);
ab_blah = ab_blah +1
if(ab_blah <= 10){
setTimeout(animate_block(){ab_blah},30);
}
? And if it shouldn't which bit(s) have I got wrong?
Ta!
setTimeout
takes a function as first argument. You can create a function on the fly, which has access to the ab_blah
because functions have access to the parent scope.
animate_block(blah);
function animate_block(ab_blah) {
move_block(ab_blah);
ab_blah = ab_blah +1
if (ab_blah <= 10) {
setTimeout(function() { animate_block(ab_blah); }, 30);
}
}
Read this article on closures in JS to get a good understanding.