Kevin Van Ryckegem
Kevin Van Ryckegem

Reputation: 1945

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.

Upvotes: 1

Views: 1301

Answers (3)

Basu
Basu

Reputation: 131

= is for assignment and == is equality check (=== for strict check). Please use equality check to fix your code.

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

Upvotes: 1

jkeys
jkeys

Reputation: 431

You were accidentally assigning values in your if statement. Try this to fix it.

At this part

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

To fix it you can use this:

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
}

Upvotes: 0

sethro
sethro

Reputation: 2127

these lines

if(counter = MIN)

and

else if( counter = MAX )

are setting counter to MIN or MAX. You want to === triple equals (== is fine in this case) to check for equality.

Upvotes: 4

Related Questions