Adding a callback to javascript while loop

I am trying to replicate a type-type effect on my resume page and have, if it works, with the exception of one part:

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

This is a function that writes lines and works correctly, except that it writes all lines at once. I would like him to write one line, then move on to the next and so on and so forth. I know that the solution is to add a callback function, but I cannot get it to work correctly. Any help / advice would be appreciated. Thank!

Also here is the full jsfiddle .

+4
source share
1 answer

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

+5

All Articles