0

嗨,我发现了这个模拟打字机效果的片段:

$.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);
    });
};

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

$.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();
    });
};

但它在进程完成之前执行

我怎么知道在哪里放置这个回调函数?

4

2 回答 2

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
    });

};
于 2013-04-23T15:07:05.337 回答
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

});
于 2013-04-23T15:11:21.407 回答