Bryce
Bryce

Reputation: 309

My function isn't returning

Ehllo! My function isn't returning (exiting) when conditions are met.

var arrowReady = false;
var arrowImage = new Image();
var deg = 0;
arrowImage.onload = function () {
    arrowReady = true;
    function moveArrow() {
        setInterval(function() {
            ctx1.save();
            deg++;
            ctx1.rotate(deg * Math.PI / 180);
            // Here is  ^  the amount of degrees it turns.
            ctx1.clearRect(300, 200, 52, 310);
            ctx1.drawImage(arrowImage, 300, 100, 42, 300);
            ctx1.restore();
        }, 100);

        if (deg == 40) return;

    }
}

From my understanding, when deg = 40, the function should stop. But, it's not. Any suggestions?

Upvotes: 0

Views: 73

Answers (3)

David
David

Reputation: 218877

It's not clear what that last conditional is even supposed to do. There's nothing after it, so the function is going to stop execution there anyway. Why does it matter if deg == 40 if that's where the function call ends no matter what?

More to the point, I'm sure, is the fact that the function in question doesn't actually change the value of deg. So deg will never equal 40 on that line. What you're doing is queuing up another function to run at a later time (100 ms?). After that function is queued up, the control immediately goes to the if statement (before that other function runs).

So deg is being modified, in a completely different function scope, after the if statement executes.

Upvotes: 0

Alex Mcp
Alex Mcp

Reputation: 19315

Tricky javascript going on here. moveArrow is only called once on document load. returning or not will not stop your interval from running.

You need to save a reference to the interval:

var interval = setInterval(...

And then from WITHIN the anonymous setInterval function, when deg ==40 you will want to clearInterval(interval) to stop it from running.

Try this:

var arrowReady = false;
var arrowImage = new Image();
var deg = 0;
arrowImage.onload = function () {
    arrowReady = true;
    function moveArrow() {
        var interval = setInterval(function() {
            if (deg == 40) {
              clearInterval(interval);
              return;
            }
            ctx1.save();
            deg++;
            ctx1.rotate(deg * Math.PI / 180);
            // Here is  ^  the amount of degrees it turns.
            ctx1.clearRect(300, 200, 52, 310);
            ctx1.drawImage(arrowImage, 300, 100, 42, 300);
            ctx1.restore();
        }, 100);

    }
}

Upvotes: 2

06needhamt
06needhamt

Reputation: 1605

I am not a JavaScript programmer but don't you need to specify a value to return

EXAMPLE if (deg == 40) return deg;

Upvotes: 0

Related Questions