Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

How to add a callback to ths function?

Hi there I found this snippet that simulates the Typing machine effect:

$.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 seems to work great but I need to know when the function has finished, I tried to add Another parameter and run it at the end of it:

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

But its executed before the proccess finished

How can I know where to place this callback function?

Upvotes: 0

Views: 146

Answers (2)

moonwave99
moonwave99

Reputation: 22817

Check the condition inside the setTimeout callback:

$.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

});

Upvotes: 0

colestrode
colestrode

Reputation: 10658

Call it for the last element in the each, this will call the callback after the animation has been applied to each letter

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

};

Upvotes: 1

Related Questions