简体   繁体   English

循环时向javascript添加回调

[英]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 . 此外,这里是完整的jsfiddle

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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM