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
6
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Dec 1, 2015 at 22:07
  • Where are you setting actualColor? Commented Dec 1, 2015 at 22:09
  • You don't give your variables any value. Commented Dec 1, 2015 at 22:11
  • I left this part out in this code snippet. It would have been too long. There is a comment inside the code. Commented Dec 1, 2015 at 22:12
  • If i set a number to prevColor in line 2 the console will always log this value. But no updated Color Commented Dec 1, 2015 at 22:15

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.