0

I have 2 variables

var firstThumb = 2;             
var thumbRel = "0" + firstThumb;

This sets the number for my first thumbnails rel attribute rel="02" - I like things looking nice, there are 15 thumbs so it just makes my code line up and look nicer. That's the reason for the 0.

I have a function.

function thumbIncrease() {
      firstThumb++
   };

this runs in an interval - Every 2 seconds.

setInterval(function(){
   thumbIncrease();
   console.log(firstThumb);
   console.log(thumbRel);
}, 2000);

the console log for firstThumb increases as expected - 2, 3, 4, 5 and so on every 2 seconds.

BUT - The console log for thumbRel stays at 02 every time and doesn't increase

So I guess thumbRel isn't updating when firstThumb does for some reason?

Could anybody help with this?

Thanks!!

1

3 Answers 3

3

Try this: http://jsfiddle.net/csdtesting/o7x1smq5/

var firstThumb = 2;             
var thumbRel = "0"; 

function thumbIncreases() {
      firstThumb++;
      thumbRel = "0" +firstThumb;
   };

setInterval(function(){
   thumbIncreases();

   console.log(firstThumb);
   console.log(thumbRel);
}, 2000);
Sign up to request clarification or add additional context in comments.

Comments

2

You have defined the thumbRel as 02 and you are not updating it directly anywhere. It is not referenced, but read&used. In order to update both, could this help?

function thumbIncrease() {
      firstThumb++;
      thumbRel = "0" + firstThumb;
};

Comments

1

When you say

var thumbRel = "0" + firstThumb;

Javascripts uses the current value of firstThumb to calculate thumbRel, in this case "02". However, after that, the variable are completely seperate from each other. It will behave as if you wrote:

var thumbRel = "02";

Most programming languages behave that way. If you use the = sign to assign a vaiable to a value, it will stay the same until you assign another value to it.

If you want the value to change based on the value of firstThumb, you should consider using a function instead of a variable, like this:

var firstThumb = 2;
var thumbRel = "0" + firstThumb;

function thumbRel () {
  return "0" + firstThumb;
}

function thumbIncrease() {
  firstThumb++
};

setInterval(function(){
   thumbIncrease();
   console.log(firstThumb);
   console.log(thumbRel());
}, 2000);

EDIT: fixed function call

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.