Javascript setTimeout运行两次?

时间:2012-09-11 14:32:59

标签: javascript jquery settimeout setinterval

$(document).ready(function(){
    $('#home-buzz-1').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});

    setTimeout("$('#home-buzz-2').css('display','inline');$('#home-buzz-2').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});",3000);

    setTimeout("$('#home-buzz-3').css('display','inline');$('#home-buzz-3').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});",4500);
});

我正在尝试使用Fancy Typewriter插件在此页面上编写动画脚本 - 该插件将文本置于元素内部,并使用它制作一个很好的打字动画。但是最后两个具有setTimeout函数的div运行两次。我的想法是,我想要一个div来制作动画,然后在前一个div完成后制作下一个动画。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

你不应该将字符串传递给setTimeout函数,试试这个:

$(document).ready(function(){
    $('#home-buzz-1').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});

    setTimeout(function(){
        $('#home-buzz-2').css('display','inline');
        $('#home-buzz-2').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});}
    ,3000);

    setTimeout(function(){
        $('#home-buzz-3').css('display','inline');
        $('#home-buzz-3').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});}
    ,4500);
});

答案 1 :(得分:0)

@zzzzBov是对的,JS是功能语言:

setTimeout(function()
{
    $('#home-buzz-3').css('display','inline');
    $('#home-buzz-3').fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true});
},4500);

因此setTimout需要传递函数,而不是字符串常量。它与$(document).ready(function(){});< - 几乎相同 - 你一直将函数作为参数传递。

答案 2 :(得分:0)

不需要setTimeouts,插件完成后会有回调。

$(function(){
    function addTypeWriter(elemId) {  //You copy pasted the same thing over and over, make a helper function!
        jQuery(elemId).show().fancyTypewriter({type:true, steps:3, timeBetweenSteps:25, 'mouseOver': false, underScore:true, callback: nextOne});
    }  //chaining does the body good. Notice the callback, read the docs!
    var typewriters = ["#home-buzz-1","#home-buzz-2","#home-buzz-3"];  //elements you want to apply the effect to in sequential order
    function nextOne() {  //this is what we call
        if(typewriters.length==0) {  //if length is greater than zero, we have things to run!
            return;
        }
        var elem = typewriters.shift();  //remove first item from the array
        addTypeWriter(elem);  //fire off the annimation
    }
    nextOne(); //start it off
});