Infinite setInterval even though it should've cleared?

How come that the setInterval doesn't clear it self?... with each loop globalAlpha is 0.1 more. Yet even though it stops incrementing at 1. The loop just keeps going??

MY full code at, this is at the bottom of the file: https://github.com/GunZi200/Memory-Colour/blob/master/test.js

function secondCanvasFirst(){
    //if (collides(secondCanvas, exx, eyy)) {
    console.log("true");
    var j = 0, 
    i = setInterval(function () {
        context.globalAlpha = j;
        context.fillStyle = '#F8F8FF';
        context.fillRect(0, 0, x, y);
        j += 0.1;
        console.log(context.globalAlpha);
        if (context.globalAlpha.toFixed(0) === 1) {
            clearInterval(i);
            userTurn = true;
            b_canvas.addEventListener('click', clickEvent, false);
            alert("hi");
            second = true;
            game_interface();
        }
    }, 100);
}
        var clickEvent1 = function clickEvent1(e) {
            new FastClick.attach(document.body);
            console.log("clickevent1");
            exx = e.offsetX;
            eyy = e.offsetY;
            secondCanvasFirst();
        }

        if (b_canvas && b_canvas.getContext) {
            b_canvas.addEventListener('click', clickEvent1, false);
            FastClick.attach(document.body);
        }

Upvotes: 0

Views: 59

Answers (2)

David
David

Reputation: 4873

So, essentially when you have:

i = setInterval(function () {

i is undefined. As in, it doesn't even exist. So when you get to this part

clearInterval(i);

It says, i? What's that? Now I think JS has some capability to where it would derive that i is a variable, but I'm guessing that because you're passing it into another inner function, that that is where the issue comes into play.

So

var i = setInterval(function () {

should solve your problem

Upvotes: 1

softwarenewbie7331
softwarenewbie7331

Reputation: 967

try replacing

context.globalAlpha.toFixed(0) === 1 

with

context.globalAlpha > 0.95

toFixed converts your value to a String, which is not what you want.

Upvotes: 3

Related Questions