Tuesday 6 June 2017

Javascript variable not changing inside setInterval() function?

The variable counter does not change for some reason, it stays its initial value, of 50. It's a global variable, that is tried to be changed inside a function called by setInterval().

var mode = false;
var counter = 50;
var interval = null;
var increment = false;
var MAX = 50;
var MIN = 0;
var INTERVAL_MS = 3000;

setInterval(doInterval, INTERVAL_MS);

function doInterval() {
    if(increment)
    {
        counter += 1;
    }
    else
    {
        console.log("Decrement, " + counter);
        counter -= 1;
    }

    // Set direction
    if(counter = MIN)
    {
        increment = true;
    }
    else if(counter = MAX)
    {
        increment = false;
    }

    console.log("set to " + counter + " (D) Increment next time? " + increment);

    // dosomething with the values
}

The output from this code

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

And so on

Since it's 50 and increment is false, it should become 49, 48, however it seems that I can't change the variable's value. What could be a reason? The code is run inside a NodeJS app.



via Kevin Van Ryckegem

No comments:

Post a Comment