4

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.

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

That is pretty awesome, does exactly what I want. Thanks for the quick response. Where is a good spot to views some docs on the setTimeout idea?
This is pretty neat. But I don't like the outcome, personally. One has to wait and see all the content load.
MDN generally has good documentation on JavaScript.
@yellen - that's what the OP asked for, and in some cases it can be neat, as long as one knows that the visitor will sit around and wait for it I suppose.
@adeneo - Sorry, was not targeted to your solution. :P
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.