+ 1
Help me understand why this code deosn't work, and how I can fix this
I'm still a begginer, I just learned about the setInterval and clearInterval methods today and I wanted to play around with these a little to understand these, I wanted to make a button that will make alerts appear every 6 seconds, and a button that will make them stop appearing, but for some reason it doesn't work, here is my code: https://code.sololearn.com/WUncvKZLhywf/#js
7 Réponses
+ 1
Something like that
var alertInterval
function fu(){
alert("Hello World!");
};
function example8(){
this.start = function(){
alertInterval = setInterval( fu, 6000);
};
this.stop = function(){
clearInterval(alertInterval);
};
};
var alerts = new example8();
+ 6
You can write it this way too because alertInterval is only required within example8() :
function example8(){
var alertInterval
this.start = function(){....}
this.stop = function(){....}
}
+ 2
When you declare a variable inside a function it become local and accessible only inside the function so when you try to reach it from another function it will give you the reference error that the variable is undefined so you declare it outside as global and then work with it inside the function
+ 1
@Ruba Kh when I do it the alerts start appearing before I click the button, see: https://code.sololearn.com/WSWITXAyv4pl/#html
0
Try declaring var alertInterval outside the functions
0
The code I shared now is working with me
0
I don't know why it works but it works, thanks @Ruba Kh