Reputation: 20163
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
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
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