1

I have a number in a object value that I want to dynamically update as the code runs. So for example, if the value of the number is 30, when I run my code, I want to be able to update this number to say.. 20 without me actually having to go into the code and personally update it to 20.

How can I write code that will update this object value? The trouble I'm having is with a timer system that keeps registering the value of 30 every 1 second instead of the NEW value assigned to it after subtracting some numbers.

var count = character.energy; // My Energy level is 30
var counter = setInterval(timer, 1000); 

function timer() { 
  count += characterstats.energyregen;
  if (count >= 30){
     clearInterval(counter);
  }
  document.getElementById("energy").innerHTML = count;
  character.energy = count;
}
Shawn
  • 1,175
  • 2
  • 11
  • 20

2 Answers2

3

Move the declaration and initialization of the count variable inside the timer.

var counter = setInterval(timer, 1000); 

function timer() { 
  var count = character.energy; // My Energy level is 30
  count += characterstats.energyregen;
  if (count >= 30){
     clearInterval(counter);
  }
  document.getElementById("energy").innerHTML = count;
  character.energy = count;
}
Mike Edwards
  • 3,742
  • 17
  • 23
0

Another way, but may not be what you are looking for , is using local Storage and or cookies to store the value. Though, use judgment on this depending on how important or private the variable information is. I have done this, and encrypted it before storing. I have stored the value in localStorage, then the object is updated durring load event, to get the new value. A getter/setter type function is a property on the object, so that it increments what ever you want, everytime the script is ran. I do this by storing the object, as a string running JSON on it. If you need it to be updated based on a timed theme, then Mike's answer is a good one. If you were only using a timer, because you were not sure of another method, try out the localStorage option. Has been useful in some instances for me. Happy coding! :)

Reference to good post for storing objects in HTML5 localStorage: https://stackoverflow.com/a/2010948/2762516 from a fellow stack user!

SORRY! I MISREAD THE QUESTION. I thought you wanted to update every time code ran, not while code is running. I apologize:)

Community
  • 1
  • 1
Casey ScriptFu Pharr
  • 1,672
  • 1
  • 16
  • 36