0
\$\begingroup\$

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/

\$\endgroup\$
0
\$\begingroup\$

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.

The way your code is currently structured, you need those variables to be global variables (declared outside any function) and not declared within a function. This will allow the variables to exist across your different function calls.

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.

\$\endgroup\$
  • \$\begingroup\$ Is it possible that I can make them global variables and still only run them when the gameStart() loop is run? \$\endgroup\$ – Geroy290 Jul 19 '14 at 22:27
  • \$\begingroup\$ Yes, they are just variables. They can be global if you want them to be and only put a value in them when you want. \$\endgroup\$ – jfriend00 Jul 19 '14 at 22:31
  • \$\begingroup\$ Yes but it runs timer even when I haven't clicked the start button \$\endgroup\$ – Geroy290 Jul 19 '14 at 22:32
  • \$\begingroup\$ 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. \$\endgroup\$ – jfriend00 Jul 19 '14 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.