clearInterval() not working [duplicate]
setInterval returns an ID which you then use to clear the interval.
setInterval returns an ID which you then use to clear the interval.
I am working on a music program that requires multiple JavaScript elements to be in sync with another. I’ve been using setInterval, which works really well initially. However, over time the elements gradually become out of sync which is bad in a music program. I’ve read online that setTimeout is more accurate, and you can … Read more
Use a counter which increments each time the callback gets executed, and when it reaches your desired number of executions, use clearInterval() to kill the timer:
A lot of other answers are focusing on a pattern that does work, but their explanations aren’t really very thorough as to why your current code doesn’t work. Your code, for reference: Let’s break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting “test”. … Read more
Why is it not accurate? Because you are using setTimeout() or setInterval(). They cannot be trusted, there are no accuracy guarantees for them. They are allowed to lag arbitrarily, and they do not keep a constant pace but tend to drift (as you have observed). How can I create an accurate timer? Use the Date object instead to get the (millisecond-)accurate, current time. Then base … Read more