# How to use setInterval and clearInterval

I have a game that I am making and cannot seem to get the setInterval and clearInterval methods to work. When I debug it in the browser console it shows that the method is still being called over and over again. I am wondering how can I get it to actually stop and then restart afterwards without going faster than it was before (which often happens with setInterval and clearInterval). Notice that when it goes back to the menu, and you click Start again that the timer is running multiple times on the money. Any help is much appreciated, please take a look at this fiddle demo: http://jsfiddle.net/Xn4qT/

Your increaseMoney and gameTimerEnd variables are local variables so they only last the duration of the function they are declared in. Thus, when you try to call clearInterval() using them, the variables no longer exist.
Also, it does not make sense that you're using setInterval() for the gameTimer because you're just clearing the interval the first time it fires. Perhaps you should use setTimeout() instead and then you won't even have to clear it because setTimeout() just fires once.
• Is it possible that I can make them global variables and still only run them when the gameStart() loop is run? – Geroy290 Jul 19 '14 at 22:27
• No. You only put var gameTimerEnd; at the global scope and make sure there is no var in front of it inside the function. Then, the variable all by itself is declared in the global scope and you can assign to it from within your function and it will last from one function to the next. Same for the other one. – jfriend00 Jul 19 '14 at 22:35