質問

How could I fix this problem? I have a word represented on the screen repeatedly with fadeIn.delay.fadeOut. If I pick this word randomly from an array, it does not exactly behave as I want.

I want to have the word, fade it out, and have the new word faded in. Now, it appears that the 'word change' happens too soon, see example on fiddle

Code:

var words = ["A", "B", "C", "D"];
var showwords = function() {
var newword = words[Math.floor((Math.random() * words.length))]
$("#words").text(newword)
            .fadeIn(50)
            .delay(2000)
            .fadeOut(500);
}
setInterval(showwords, 2000)

Can anyone help me with this?

役に立ちましたか?

解決

http://jsfiddle.net/8VHR5/3/

I don't think your original code was queueing the fadeout, delay, and then fadein properly. Try it like this using the callback function of fadeOut so that the next bit of code only executes after that has completed.

var words = ["A", "B", "C", "D"];
var showwords = function() {
    var newword = words[Math.floor((Math.random() * words.length))]
    $("#words").fadeOut( 1000, function() {
         $("#words").text(newword).fadeIn(1000);
    });
}
setInterval(showwords, 3000)

他のヒント

Instead of

setInterval(showwords, 2000)

put an amount equal or greater than 2550 (50 + 2000 + 500)

setInterval(showwords, 2600)

Try

 var words = ["A", "B", "C", "D"];
 var showwords = function() {
 var newword = words[Math.floor((Math.random() * words.length))]
 $("#words").text(newword)
            .fadeIn(1000)
            .fadeOut(1000);
}
setInterval(showwords, 2000)

http://jsfiddle.net/8VHR5/1/

You want to leverage the callback function and think about it a little differently:

function showWords(){
    var newWord = words[Math.floor(Math.random() * words.length)];

    $('#words').fadeOut(500,function(){
        $(this).text(newWord).fadeIn(500);

        setTimeout(showWords,2000);
    });

}

Notice the use of setTimeout instead of setInterval, as you have a recursive function called.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top