-3

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)            
        }                       
    });
});
Brad Larson
  • 170,088
  • 45
  • 397
  • 571

1 Answers1

2

(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 time 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>
Tyler Chong
  • 650
  • 2
  • 12
  • 24