Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

hello Im trying to do a memory game project I got an issue with the timer it keeps counting after the game is over

/* *Timer */ const timerContainer =document.querySelector(".timer"); let liveTimer, totalSeconds = 0;

//Set the default value to the timer timerContainer.innerHTML = totalSeconds + 's';

function startTimer(){ liveTimer = setInterval(function(){ totalSeconds++; timerContainer.innerHTML = totalSeconds + 's'; },1000); }

function stopTimer() { clearInterval(liveTimer); }

html { box-sizing: border-box; }

*, *::before, *::after { box-sizing: inherit; }

html, body { width: 100%; height: 100%; margin: 0; padding: 0; }

body { background: #ffffff url('../img/geometry2.png'); /* Background pattern from Subtle Patterns */ font-family: 'Coda', cursive; }

.container { display: flex; justify-content: center; align-items: center; flex-direction: column; }

h1 { font-family: 'Open Sans', sans-serif; font-weight: 300; }

/*

  • Styles for the deck of cards */

.deck { width: 660px; min-height: 680px; background: linear-gradient(160deg, #02ccba 0%, #aa7ecd 100%); padding: 32px; border-radius: 10px; box-shadow: 12px 15px 20px 0 rgba(46, 61, 73, 0.5); display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; margin: 0 0 3em; }

.deck .card { height: 125px; width: 125px; background: #2e3d49; font-size: 0; color: #ffffff; border-radius: 8px; cursor: pointer; display: flex; justify-content: center; align-items: center; box-shadow: 5px 2px 20px 0 rgba(46, 61, 73, 0.5); }

.deck .card.open { transform: rotateY(0); background: #02b3e4; cursor: default; }

.deck .card.show { font-size: 33px; }

.deck .card.match { cursor: default; background: #02ccba; font-size: 33px; }

.deck .card.disable { pointer-events: none; }

/*

  • Styles for the Score Panel */

.score-panel { text-align: left; width: 345px; margin-bottom: 10px; }

.score-panel .stars { margin: 0; padding: 0; display: inline-block; margin: 0 5px 0 0; }

.score-panel .stars li { list-style: none; display: inline-block; }

.score-panel .restart { float: right; cursor: pointer; }

.fa-star { color: #FFD700; } .timer { display: inline-block; margin: 0 2rem; }

1 Answer

Steven Parker
Steven Parker
243,160 Points

At first glance, the snippet shown here seems OK, but the issue might be in how these functions are called by the other code. To enable a complete analysis, share the entire code (best done with a repo or workspace snapshot link).

/*

  • Create a list that holds all of your cards */ const icons= ["fa fa-diamond","fa fa-paper-plane-o", "fa fa-anchor","fa fa-bolt","fa fa-cube","fa fa-anchor", "fa fa-leaf", "fa fa-bicycle","fa fa-diamond", "fa fa-bomb", "fa fa-leaf", "fa fa-bomb","fa fa-bolt", "fa fa-bicycle", "fa fa-paper-plane-o", "fa fa-cube"];

const cardsContainer = document.querySelector(".deck"); let openedCards = []; let matchedCards = []; /* *Start Game */

function init(){ //Cards for (let i = 0; i <deck.length; i++){ const card = document.createElement("li"); card.classList.add("card"); card.innerHTML =`<i class="${deck[i]}"></i>`; cardsContainer.appendChild(card);

//Add Click Event
click(card);
}

}

/* *Click Event */

//First Click let isFirstClick= true;

//Click Function function click(card){

//Card Click
card.addEventListener("click", function(){

    if(isFirstClick){
        startTimer();
        isFirstClick = false;
    }

    const currentCard = this;
    const previousCard = openedCards[0];

//We have an existing Opened card
    if(openedCards.length === 1) {

        card.classList.add("open", "show",  "disable");
    openedCards.push(this);

    //Compeare our 2 opened cards
    compare(currentCard, previousCard);

    }else{
        currentCard.classList.add("open", "show",  "disable");
        openedCards.push(this);
    }
});

} /* *Compare Cards */

function compare(currentCard, previousCard){

    //Matcher
    if(currentCard.innerHTML === previousCard.innerHTML) {

        //Matched
        currentCard.classList.add("match");
        previousCard.classList.add("match");

        matchedCards.push(currentCard, previousCard);
        openedCards = [];

        //Check is game is over
        isOver();

    }else{

        //Wait 630ms then do this
        setTimeout(function(){
            currentCard.classList.remove("open", "show", "disable");
            previousCard.classList.remove("open", "show", "disable");
        },630);

        openedCards = [];

    }
    //Add New  Move
    addMove();
}

/*
*Check if the game is over
*/

function isOver(){ if(matchedCards.length === isSecureContext.length){

    //Stop timer
    stopTimer();

    alert("You Win!");
   }

}

/* *Add Move */ const movesContainer = document.querySelector(".moves"); let moves = 0; movesContainer.innerHTML = 0; function addMove(){ moves++; movesContainer.innerHTML = moves;

  //Set Rating
  rating();

} /* *Rating */ const starsContainer = document.querySelector(".stars"); const star = <li><i class="fa fa-star"></i></li>; starsContainer.innerHTML = star + star + star; function rating() { if(moves <6){ starsContainer.innerHTML =star + star + star; }else if(moves < 10) { }else{ starsContainer.innerHTML = star; } }

/* *Timer */ const timerContainer =document.querySelector(".timer"); let liveTimer, totalSeconds = 0;

//Ste the default value to the timer timerContainer.innerHTML = totalSeconds + 's';

function startTimer(){ liveTimer = setInterval(function(){ totalSeconds++; timerContainer.innerHTML = totalSeconds + 's'; },1000); }

function stopTimer() { clearInterval(liveTimer); }

/*

  • Restart Button */ const restartBtn = document.querySelector(".restart"); restartBtn.addEventListener("click", function() { //Reset ALL cards cardsContainer.innerHTML = "";

    // Call init to create new cards init();

    // Reset the game reset();

});

/*

  • Reset All Game */ function reset() { // Empty matchedCards array matchedCards = [];

    // Reset moves moves = 0; movesContainer.innerHTML = moves;

    // Reset rating starsContainer.innerHTML = star + star + star;

    /*

    • Reset the timer
    • - Stop it first
    • - Then, reset the isFirstClick to true to be able to start the timer again!
    • - Don't forget about totalSeconds, it must be 0
    • - One more thing, is to update the HTML timer's container */ stopTimer(); isFirstClick = true; totalSeconds = 0; timerContainer.innerHTML = totalSeconds + "s"; }

/////// Start the game for the first time! init();

// /* // * Display the cards on the page // * - shuffle the list of cards using the provided "shuffle" method below // * - loop through each card and create its HTML // * - add each card's HTML to the page // */

// Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex;

while (currentIndex !== 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
}

return array;

}

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Matching Game</title> <meta name="description" content=""> <link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css"> <link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda"> <link rel="stylesheet" href="css/app.css"> </head> <body>

<div class="container">
    <header>
        <h1>Matching Game</h1>
    </header>

    <section class="score-panel">
        <ul class="stars">

        </ul>

        <span class="moves">0</span>"Move(s)
        "
        <span class="timer">0 mins 0 secs</span>

        <div class="restart">
            <i class="fa fa-repeat"></i>
        </div>
    </section>

    <ul class="deck">


    </ul>

</div>

<script src="js/app.js"></script>

</body> </html>

Steven Parker
Steven Parker
243,160 Points

That code is a bit hard to read (or run!) in the current state. A workspace snapshot link would be ideal, but if you must post code directly, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.