Search code examples
javascriptjquerycallbackjquery-callback

Adding callback to javascript while loop


I am trying to replicate a type-writer effect on a resume page of mine, and have if working except for one part:

while (i < tags.length) {
    type(tags[i], content[i], 0, 50);
    i++;
}

This is the function that writes out the lines, and it works correctly, except for the fact that it writes all of the lines at once. I would like for it to write a single line, then move on to the next, and so on and so forth. I know the solution lies in adding a callback function in but I can't seem to get it to work right. Any help/advice would be appreciated. Thanks!

Also, here is the full jsfiddle.


Solution

  • A callback and a recursive function seems like the way to go

    var type = function (target, message, index, interval, callback) {    
        if (index < message.length) { 
            $(target).append(message[index++]); 
            setTimeout(function () { 
                type(target, message, index, interval, callback); 
            }, interval); 
        } else {
            callback();
        }
    }
    
    var i = 0;
    
    (function recursive() {
        if (i < tags.length) {
            type(tags[i], content[i], 0, 50, recursive);
            i++;
        }
    })();
    

    FIDDLE