0

It's my first question here. I was looking for a similar topic but I didn't find the answer that I could use. I would like to get a timer in my memory game that displays current time (I want to use Date object). I used a function from here How to create an accurate timer in javascript? but after the first click on the card, the time does not begin from 0. It shows the time that has elapsed since the page loading.

//variable for timer
var gameScore = $(".score-game");
var timer = $("#timer");
gameScore.html("0 seconds");
var hasGameStarted = false;
var score = Date.now();

    //timer function
    function countdownTimer() {
        if (hasGameStarted !== true) {
            scoreTimeout = setInterval(function() {
                var delta = Date.now() - score;
                gameScore.html(Math.floor(delta / 1000) + " seconds");
            }, 1000);
            hasGameStarted = true;
        }
    }
cards.on('click', function() {
countdownTimer();
});

If you want to see how works my game, check this site (timer is working good now but does not display time from date object):

https://borkson.github.io/Cars-Memory-Game/

Sorry for my English :(

Community
  • 1
  • 1
borkson
  • 43
  • 4

2 Answers2

0

I understand your code, you mean that you start a timer calculated by delta variable and updated every 1000 milliseconds

//variable for timer
var gameScore = $(".score-game");
var timer = $("#timer");
gameScore.html("0 seconds");
var hasGameStarted = false;
var score = Date.now();

//timer function
function countdownTimer() {
  if (hasGameStarted !== true) {
    scoreTimeout = setInterval(function() {
      var delta = Date.now() - score;
      gameScore.html(Math.floor(delta / 1000) + " seconds");
    }, 1000);
    hasGameStarted = true;
  }
}

$("#cards").on('click', function() {
  countdownTimer();
});
#cards {
    border-radius: 25px;
    background: #73AD21;
    padding: 20px;
    width: 200px;
    height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<img id="cards"></img>
<div class="score-game">score</div>
<div id="timer">timer</div>
nazimboudeffa
  • 939
  • 6
  • 20
0

Perhaps there is a more-clever way, but you could...

var startTime = Date.now();

...then below, in your function...

var delta = startTime - score;

Does that help?

  • id didn't work because i had variable for Date.now() before (var score). Now it is looks like: var score = Date.now(); var startTime = Date.now(); function countdownTimer() { if (hasGameStarted !== true) { scoreTimeout = setInterval(function() { var delta =startTime - score; gameScore.html(Math.floor(delta / 1000) + " seconds"); }, 1000); hasGameStarted = true; } } – borkson Nov 14 '16 at 00:21
  • try to use the js snippet tool it's a nice feature and helps to read code – nazimboudeffa Nov 14 '16 at 17:01