1

I'm trying to create a program where there are two variables x and y where they continually increment every 2 seconds. 2, 4, 6, 8, etc. I also want a reset button where once pressed, x and y become 0 and 1 respectively.

However the logic problem I'm having is how to get the function return values to be constantly assigned in a changing status to the global variables. I used an array with the name z to hold the x and y values and had x=z[0] and y=z[1], to transfer the multiple return values from the function. Like [a,b].

How do I continually tell the program that each time I increment x and y in my increase() function, that I want x and y to equal the new value? Because the current logic I'm trying to figure out should work once, but instead it doesn't work at all. Instead the values don't continually increase and x and y only increase once from 1 and 2 to 2 and 3 and never more. The reset button doesn't work. I don't know how to transfer the function return values to global values without the values being encapsulated in the function.

var x = 1;
var y = 2;
var z = [x, y];
x = z[0];
y = z[1];


function reset() {
  a = 0;
  b = 1;
  return [a, b];
}


function increase(a, b) {
  a++;
  b++;
  return [a, b];
}

function consoles(a, b) {
  console.log(a);
  console.log(b);
}

var clockTimer;
clockTimer = setInterval(function() {
  z = increase(x, y);
}, 2000);
x = z[0];
y = z[1];

var consoleTimer;
consoleTimer = setInterval(function() {
  consoles(z[0], z[1]);
}, 2000);
<input type="button" id="button" value="Reset" onclick="z=reset()"></input>

1 Answer 1

1

The problem is that when you do z = increase(x, y);, you're passing the current value of x and y - but x and y only get assigned to once (well, twice, but the same thing is assigned both times):

x = z[0];
y = z[1];

If the z array changes, the values that x and y point to do not get changed accordingly.

If I were you, I'd choose one data structure, and ditch the other - either use an array, or use separate variables for each number, but not both, to avoid confusion like this:

var x = 1;
var y = 2;

function reset() {
  x = 0;
  y = 1;
}


function increase() {
  x++;
  y++;
}

setInterval(function() {
  z = increase(x, y);
}, 2000);

var consoleTimer;
consoleTimer = setInterval(function() {
  console.log(x, y);
}, 2000);
<input type="button" id="button" value="Reset" onclick="z=reset()"></input>

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

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.