+ 1
I don't understand why my buttons only work 1 time. Could someone please help me?
5 Respuestas
+ 4
Check your variable scopes.
// no vars in global scope
window.onload = function(){
// onload() scope
var t1 = setInterval(changecolor,1000);
function time(){
// time() scope
var t1 = setInterval(changecolor,1000);
}
When you call time(), t1 is created and exists in the time() function.
When the function exits, the variable "falls out of scope" and is destroyed.
When you try to clear t1 in another function, you're clearing t1 from onload() and not time().
Note, Javascript allows you to clear an interval that's already been cleared (nothing happens).
+ 4
'var' declares a new variable right at that spot (so... within the function, but not outside it).
If you omit 'var', Javascript will search "up" to see if the variable has already been declared.
If it searches up until it reaches the global scope, it will declare a variable there for you:
window.onload = function() {
function set() {
t1 = 'hello';
}
set();
alert(t1); // this works!
}
Wherever Javascript finds the variable declared (even if it creates it for you), that's where it will be set.
Process:
is there a var declared in set()? [No]
Is there a var declared in onload()? [No]
is there a global var? [No]
Create global var
now that it's declared, set it
end of function, then alert
Does this help, when I suggest you remove 'var' within the time() function?
0
I haveI noticed that when you press the he notado que al presionar el botola I noticed that by pressing the "Rest" button de la animación, fíjate en eso....of the animation, look at that ..
0
@Kirk Schafer So how could I save a variable if I need to delete it and then use it again? Thank you for the help (sorry for my English)
0
@Kirk Schafer thank you very much for the help.