Ric SSalvacion Ric SSalvacion - 4 years ago 342
HTML Question

Javascript Memory

I was wondering why my program crashes after its made its first match....any ideas would be greatly appreciated. Below is the code snippet. Thanks for the input!

var clicks = 0; //counts how may picks have been made in each turn
var firstchoice; //stores index of first card selected
var secondchoice; //stores index of second card selected
var match = 0; //counts matches made
var backcard = "deck.jpg"; //shows back of card when turned over

var faces = []; //array to store card images
faces[0] = 'pic1.jpg';
faces[1] = 'pic2.jpg';
faces[2] = 'pic3.jpg';
faces[3] = 'pic3.jpg';
faces[4] = 'pic2.jpg';
faces[5] = 'pic1.jpg';

function choose(card) {
if (clicks === 2) {
return;
}
if (clicks === 0) {
firstchoice = card;
document.images[card].src = faces[card];
clicks = 1;
} else {
clicks = 2;
secondchoice = card;
document.images[card].src = faces[card];
timer = setInterval("check()", 1000);
}
}
/* Check to see if a match is made */

function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
clicks = 0;
return;
}
}

Answer Source

The first parameter of setInterval needs to be a function not a string pretending to be a function. So you would want this:

timer = setInterval(function() { check(); }, 1000);

Of course, you can simplify:

timer = setInterval(check, 1000);

Not sure why you're using setInterval() here. You could more easily just do:

timer = setTimeout(check, 1000);

The advantage is there is no interval to clear in the check() function.

The other issue is that you are not resetting your 'clicks' counter to 0 when there is a match.

You want this:

function check() {
    clearInterval(timer); //stop timer
    if (faces[secondchoice] === faces[firstchoice]) {
        match++;
        document.getElementById("matches").innerHTML = match;
    } else {
        document.images[firstchoice].src = backcard;
        document.images[secondchoice].src = backcard;
    }
    clicks = 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download