stumpjumper64
stumpjumper64

Reputation: 11

Javascript setInterval: first interval is abrupt

When using JavaScript's setInterval method in the example below with jQuery effects, the initial display does not appear to engage the fadeIn method. "text" is displayed suddenly.

Subsequent iterations through the chain of effects starting with fadeIn() execute as expected. It is just the first pass where the "text" is displayed suddenly without the fadeIn effect.

Any ideas as to why this occurs? Thanks - a JavaScript beginner.

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').fadeIn(1500).html("text").delay(2750).fadeOut(1500).delay(1000;
};

Upvotes: 0

Views: 819

Answers (2)

Matt Burland
Matt Burland

Reputation: 45155

Assuming your text is initially blank and hidden, you are fading in an empty element and then setting the text to text only after the element is faded in. Reverse those steps:

$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);
};
#myId { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myId">

</div>

Upvotes: 0

arsea
arsea

Reputation: 86

It could be Fading In without you noticing as the text is added after the fade In. Switch it around, add the text before fading it in. Make sure it was not displayed beforehand (in CSS or however you need it).

$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);

Upvotes: 1

Related Questions