wurstbrotrest
wurstbrotrest

Reputation: 329

setInterval function cannot use outer variable

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

Upvotes: 0

Views: 110

Answers (2)

Matiu Carr
Matiu Carr

Reputation: 298

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)

Upvotes: 1

void
void

Reputation: 36703

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);

Upvotes: 0

Related Questions