Problem with setInterval | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Problem with setInterval

All going fine, but the interval is going faster and faster each time, can you help me? Code deleted <solved>

23rd Dec 2018, 2:25 AM
Jingga Sona
Jingga Sona - avatar
5 Answers
+ 5
setInterval() stacks and never ends unless you clearInterval(): var savedInterval; function strght(){ // it's safe to clear an unset interval clearInterval(savedInterval); savedInterval = setInterval(function(){ ballY-- // it should ideally clear itself if(ballY < 0) clearInterval(savedInterval); },10) } This is limited because you can only ever have 1 shot active and it leads you the wrong way for multiple simultaneous actions. E.g., you might be tempted to start intervals for each new simultaneous shot, but I strongly recommend using one master timer and managing some kind of collection instead. Then, you don't need to track timers, you just iterate a collection and animate whatever is there.
23rd Dec 2018, 2:49 AM
Kirk Schafer
Kirk Schafer - avatar
+ 7
You need to clear the previous interval before you create a new one.
23rd Dec 2018, 2:36 AM
Toni Isotalo
Toni Isotalo - avatar
+ 4
Thank you Kirk Schafer
23rd Dec 2018, 12:46 PM
Jingga Sona
Jingga Sona - avatar
+ 3
Note, avoiding numerous timers may actually only matter if you saturate JS's event management system with lots (thousands?) of objects. It may be just fine with every animated object having its own timer (so, whatever works for you).
23rd Dec 2018, 2:59 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Thanks for reminding Toni Isotalo!
23rd Dec 2018, 2:47 AM
Jingga Sona
Jingga Sona - avatar