0

Why is prevColor always undefined?

This code should log a new color (actualColor) and the previous color (prevColor). However I cannot save into prevColor from inside the setInterval function. Where is the bug? I don´t think it is a context problem. But I´m not sure. There´s no this inside...

Can you tell me how I can save the value of actualColor in prevColor from inside the setInterval function?

var actualColor;
var prevColor;


// do some user action and change actualColor


setInterval(function () {
    // only log the color if it differs from prevColor
    if (actualColor != prevColor) {
        console.log("actualColor: " + actualColor + ", prevColor: " + prevColor);
    }
    prevColor = actualColor;
}, 100);

Console:

actualColor: acff06, prevColor: undefined
wurstbrotrest
  • 329
  • 1
  • 7
  • 17

2 Answers2

1

I think it must be your context -I made a simple webpage with all the bits you have above, and it works fine -even without setting initial values on the variables:

simple page+console

I placed your code in a script tag in the HEAD, and added

<input
    type="text"
    id="actualColor"
    />
<input
    type="button"
    onclick = "actualColor = document.getElementById('actualColor').value;"
    value = "change colour" />

to provide a way of changing actualColor in the webpage (rather than using the console)

Matiu Carr
  • 298
  • 1
  • 4
0

You need to initialize the value of the prevColor, otherwise first time it will be undefined

Just do

var actualColor;
var prevColor = "";


// do some user action and change actualColor


setInterval(function () {
    // only log the color if it differs from prevColor
    if (actualColor != prevColor) {
        console.log("actualColor: " + actualColor + ", prevColor: " + prevColor);
    }
    prevColor = actualColor;
}, 100);
void
  • 36,090
  • 8
  • 62
  • 107