开发者

Run function 2 when function 1 completes

开发者 https://www.devze.com 2023-03-28 00:41 出处:网络
I know similar questions have been asked and answered before but the truth is I just cant figure out what I need to do even after reading them.

I know similar questions have been asked and answered before but the truth is I just cant figure out what I need to do even after reading them.

The co开发者_开发百科de below is from a tutorial. It displays some text with a typewriter effect. That all works fine.

I've added an _ that moves along in front of the text like a dos cursor.

I'm trying to make the _ blink after the typewriter animation has completed.

I know (or should I say "think") I need a callback to trigger makeBlink() but I can't for the life of me figure out where to use it.

Could somebody please help me out?

var char = 0;
var caption = "";

function showCaption(obj) {
    caption = obj.attr('title');
    if(caption)
        type();
}


function type() {
    $('#caption').html(caption.substr(0, char++));
    if(char < caption.length+1)
        setTimeout("type()", 150);
    else {
        char = 0;
        caption = "";
    }
}

function makeBlink(){
    $("#cursor").html('<blink>_</blink>');
}


$(window).load(function() {
    showCaption($("#caption_span"));
    makeBlink(); // This runs whilst the text is still typing :(
});


Remove makeBlink(); from where you have it and insert it here:

function type() {
    $('#caption').html(caption.substr(0, char++));
    if(char < caption.length+1)
        setTimeout("type()", 150);
    else {
        char = 0;
        caption = "";
        makeBlink();
    }
}

PS. The HTML <blink> element is very old and not very supported. Even text-decoration: blink is hardly supported. It'd be better to use a javascript solution similar to the type() function you have. Something like:

function makeBlink(){
    var $cur = $('#cursor');
    if($cur.html())
        $cur.html('');
    else
        $cur.html('_');
    setTimeout(makeBlink, 500);
}

Or using css display or visibility.

Also you should change "type()" to type in your code to avoid using eval. (Never pass a string into setTimeout) Your tutorial is teaching you a bad practice there.


You would call makeBlink from the else branch in your type() function.

function type() {
    $('#caption').html(caption.substr(0, char++));
    if(char < caption.length+1)
        setTimeout("type()", 150);
    else {
        char = 0;
        caption = "";
        makeBlink();
    }
}

That would execute the makeBlink() function when you're done setting timers and done with the typing. As you had it before, your makeBlink() function is getting called while you are still executing timers and still doing more typing.

0

精彩评论

暂无评论...
验证码 换一张
取 消