+ 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

27th Sep 2020, 6:57 PM
Karak10
Karak10 - avatar
7 Antworten
+ 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();
27th Sep 2020, 7:05 PM
Ruba Kh
Ruba Kh - avatar
+ 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(){....} }
27th Sep 2020, 7:42 PM
Kevin ★
+ 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
27th Sep 2020, 7:23 PM
Ruba Kh
Ruba Kh - avatar
+ 1
@Ruba Kh when I do it the alerts start appearing before I click the button, see: https://code.sololearn.com/WSWITXAyv4pl/#html
27th Sep 2020, 7:05 PM
Karak10
Karak10 - avatar
0
Try declaring var alertInterval outside the functions
27th Sep 2020, 7:04 PM
Ruba Kh
Ruba Kh - avatar
0
The code I shared now is working with me
27th Sep 2020, 7:08 PM
Ruba Kh
Ruba Kh - avatar
0
I don't know why it works but it works, thanks @Ruba Kh
27th Sep 2020, 7:20 PM
Karak10
Karak10 - avatar