Slow Recursion

Let’s say you want to do something in a for loop, but you can’t seem to make it run with a delay in between loop iterations (let’s assume you’re working in something like JavaScript where the “setTimeout” function is non-blocking and will execute immediately).

Not to worry, the standard approach would be to write a recursive algorithm and do “setTimeout” before you call the next iteration of the recursion.

My solution is usually to embed a recursive algo in a closure, or self executing function. This way everything stays tight and you can define it in another higher level function so as not to make your code messy. See below:

var delay = 1000;              
var count = 100;
(function loop(i) {
    setTimeout(function() {
        // do something here
        if(--i) {
            loop(i);
        }
    }, delay);
})(count);

What’s nice about this is the fact that it negates the need for globals dedicated to the recursion. It’s also embeddable, see this example below where I output messages every 2 seconds:

 

function logMessages(msgs) {
    (function loop(i) {
        setTimeout(function() {
            var idx = i - 1;
            console.log(msgs[idx]);
             
            // if i != 0 loop again
            if(--i) {
                loop(i);
            }
        }, 2000);
    })(msgs.length);
}

logMessages(["things", "stuff", "awesome"]);

See the Pen waGBNa by Mike Newell (@newshorts) on CodePen.

Leave a Reply

Your email address will not be published. Required fields are marked *