如何为此函数添加回调?

时间:2013-04-23 15:05:32

标签: jquery jquery-plugins callback

您好我found this snippet模拟打字机效果:

$.fn.teletype = function(opts){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);

    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
        }, settings.animDelay * i);
    });
};

似乎工作得很好,但我需要知道函数何时完成,我尝试添加另一个参数并在其结束时运行它:

$.fn.teletype = function(opts,callback){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);

    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
        }, settings.animDelay * i
        callback();
    });
};

但它在进程完成之前执行了

我怎么知道这个回调函数的放置位置?

2 个答案:

答案 0 :(得分:1)

将其调用为each中的最后一个元素,这将在动画应用于每个字母后调用回调

$.fn.teletype = function(opts,callback){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);


    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
            if(i === (settings.text.length -1)) {
                callback();
            }
        }, settings.animDelay * i
    });

};

答案 1 :(得分:0)

检查setTimeout回调中的条件:

$.each(settings.text.split(''), function(i, letter){
    setTimeout(function(i){
        $this.html($this.html() + letter);
        if(i == (settings.text.length -1)){

          callback()

        }
    }, settings.animDelay * i

});