Thadeu Fernandes
Thadeu Fernandes

Reputation: 505

setInterval not repeating

I'm trying to change the background each 4 seconds but it jumps directly to the second condition and doesn't change anymore. Why is this happening?

var time = 1;
var func = function () {
    'use strict';

    if (time === 1) {
        document.getElementById("top-background").style.backgroundColor = "#000";
        time += 1;
    }

    if (time === 2) {
        document.getElementById("top-background").style.backgroundColor = "#aaa";
        time += 1;
    }

    if (time === 3) {
        document.getElementById("top-background").style.backgroundColor = "#d5d5d5";
        time -= 2;
    }

};

setInterval(func, 4000);

Upvotes: 1

Views: 962

Answers (2)

Gyt Dau
Gyt Dau

Reputation: 100

When time equals 1, you add 1 to time. This makes time equal 2. After that, you check if time equals 2, which it is! This makes you continue upwards until you reach the point where time equals to 3, and then you reset it to 1 again.

You need a way to check for only one condition. You could do this using if and elseifs:

if (time == 1) {
  // Code...
} else if (time == 2) {
  // Code...
} else {
  // Code...
  // Because it's not equal to 1 or 2, it must be 3.
} 

Or, you can also use Javascript's Switch statements.

switch(time) {
  case 1:
    // Code...
      break;
  case 2:
    // Code...
    break;
  case 3:
    // Code...
    break;
  default:
    // Something went wrong and it's not 1, 2, or 3
  } 

Upvotes: 2

kockburn
kockburn

Reputation: 17616

Try using else if

var func = function () {
    'use strict';

    if (time === 1) {
        document.getElementById("top-background").style.backgroundColor = "#000";
        time += 1;
    }

    else if (time === 2) {
        document.getElementById("top-background").style.backgroundColor = "#aaa";
        time += 1;
    }

    else if (time === 3) {
        document.getElementById("top-background").style.backgroundColor = "#d5d5d5";
        time -= 2;
    }

};

Upvotes: 6

Related Questions