Dovydas RamaĊĦauskas Dovydas RamaĊĦauskas - 4 months ago 7
jQuery Question

javascript, jquery. won't fadeOut

I am new to javascript and jquery, so, as a challenge, I am doing little game and ran into the problem today.

So, the code works like: there appears some text and after some time it needs to

fadeOut
, but it just won't
fadeOut
for me...

Here's my code:

var timeToStart = 3;
var timer = 0;

function count() {
document.getElementById("gameStarter").innerHTML = timeToStart + " s";
timeToStart = timeToStart - 1;
}

$("#start").click(function() {
$("#gameStart").fadeIn(500, function() {
timer = setInterval(count, 1000);
setTimeout(function() {clearInterval(timer);}, 4000);
if (timeToStart == 0) {
$("#gameStart").fadeOut(500)
}
});
});

Answer

(gcampbell and Patrick Evans pointed this out in the comments. As they haven't posted an answer, I'll post a CW.)

Your code here

            timer = setInterval(count, 1000);

            setTimeout(function() {clearInterval(timer);}, 4000);

            if (timeToStart == 0) {

                $("#gameStart").fadeOut(500)

            }

only runs your if statement once, before everything is finished running. Right now it passes over it once, when timeToStart still equals 3. I recommend putting your if statement inside of your count() function like this

        function count() {

        document.getElementById("gameStarter").innerHTML = timeToStart + " s";

        timeToStart = timeToStart - 1;

        if (timeToStart == 0) {

                $("#gameStart").fadeOut(500)

            }


    } 

so it checks it every times its run, instead of only once.

Live Example:

$("#gameStart").hide();

var timeToStart = 3;

var timer = 0;

function count() {

  document.getElementById("gameStarter").innerHTML = timeToStart + " s";

  timeToStart = timeToStart - 1;

    if (timeToStart == 0) {

      $("#gameStart").fadeOut(500)

    }
}

$("#start").click(function() {

  $("#gameStart").fadeIn(500, function() {

    timer = setInterval(count, 1000);

    setTimeout(function() {
      clearInterval(timer);
    }, 4000);

  });

});
<div id="gameStarter"></div>
<div id="gameStart">This is gamestart</div>
<input type="button" id="start" value="Start">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>