+ 2
Problem with setInterval
All going fine, but the interval is going faster and faster each time, can you help me? Code deleted <solved>
5 Antworten
+ 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.
+ 7
You need to clear the previous interval before you create a new one.
+ 4
Thank you Kirk Schafer
+ 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).
+ 2
Thanks for reminding Toni Isotalo!