Reputation: 3
I got two functions, increaseSpeed and decreaseSpeed. They both use clearInterval() then setInterval however something isn't right.
decreaseSpeed slows my speed from 1000 to 5000 however if I use that function 10-20 plus times the speed seems more like 100-500ms. Also if I use increaseSpeed to increase speed to 50ms and use decreaseSpeed after, decreaseSpeed won't have any effect at all.
This is the set, clear function
var updateRate = 1000;
var id = setInterval(myFunction, updateRate);
function myFunction() {
valClickedFun(1);
}
and decreaseSpeed
function decreaseSpeed(){
clearInterval(id);
updateRate = 5000;
setInterval(myFunction, updateRate);
console.log(updateRate)
};
I got a JSFiddle set up, if you click on "Decrease speed" button several times, you'll understand what I mean.
Upvotes: 0
Views: 97
Reputation: 1688
Each call to setInterval
returns a unique value. You store this in id
when you initially call setInterval
but you do not reset it in either decreaseSpeed
or increaseSpeed
as you create new intervals.
Because of this, each clearInterval(id)
call tries to clear the original interval, even if it has already been cleared. Any subsequently created intervals are left running. Instead of replacing the existing interval with a faster or slower one, increaseSpeed
and decreaseSpeed
add a new interval that runs alongside the existing ones.
Changing
setInterval(myFunction, updateRate);
to
id = setInterval(myFunction, updateRate);
should fix it.
Upvotes: 0
Reputation: 48
I took a look at your fiddle an I think I have found the problem.
When you use the increaseSpeed
and decreaseSpeed
functions you need to set the id of the interval to the new interval. This will make sure that the next time you click the Increase or Decrease speed button the previous interval will be cleared.
Example: id = setInterval(myFunction, updateRate);
Upvotes: 0