When you run a script, I noticed the variables you write out get run only once. Functions on the other hand, can be called multiple times.
Is there a way to call up a variable more than once like you can functions? Sorry no code for this one, just a question.
Edit: To clarify, I have a global variable that is used for a function. However when I try to call this variable from a seperate function, it does not register because it is now considered "local".
However, if I could call up the global variable at will, then I believe this would fix the issue.
// BLITZ SKILL // <-- My 2nd Function trying to use my global variable counter
document.getElementById("blitz").addEventListener('click', function(){
var counter = setInterval(timer, 1000); // Trying to restart timer, does
// not register counter variable.
var damage = Math.floor(Math.random() * characterstats.strength);
document.getElementById("energy").innerHTML = character.energy;
if ((damage <= 0) && (character.energy >= 5)) {
addMessage("You miss the dragon!");
character.energy -= 5;
}
else if (character.energy <= 4) {
addMessage("Not enough energy!")
}
if ((damage >= 1) && (character.energy >= 5)) {
dragon.hp -= damage;
document.getElementById("npchp").innerHTML = dragon.hp;
addMessage("You hit the dragon for " + damage + " hp!");
character.energy -= 5;
}
document.getElementById("energy").innerHTML = character.energy;
});
// 7. CODE TESTING AREA
var counter = setInterval(timer, 1000); <-- MyGlobal Variable
function timer() { //
var count = character.energy;
count += characterstats.energyregen;
if (count >= 35) {
clearInterval(counter);
}
document.getElementById("energy").innerHTML = count;
character.energy = count;
}
You are creating a new local variable called counter in your function by using var.
Just reference the global like so without using "var" which defines a new variable,
document.getElementById("blitz").addEventListener('click', function(){
counter = setInterval(timer, 1000); // <-- Trying to restart timer, does not
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.