Reputation: 589
I have a setinterval function in my javascript that I want to be as fast as possible, i.e. check the status of an event every 1ms. Is it possible that this would be asking too much from a user's browser? It seems to work just fine, but I am wondering if its a bad practice.
Upvotes: 4
Views: 3311
Reputation: 309
Ben Cherry has a good article about this where he tests different browsers to find how fast setInterval
can be before it becomes unreliable. The speed at which a setInterval
or setTimout
fires is dependent on the browser.
In particular, if you’re looking for consistent timer intervals across browsers, you have to use something >15ms.
So if you can set the time greater than 15ms you won't run into problems.
Upvotes: 0
Reputation: 487
is an while loop too slow for you?
while (condition)
{
//code block to be executed
}
i know i'm not ansering your question but, i think there is no better ways to do something like that...
Upvotes: 0
Reputation: 77986
It is not only possible, it's quite common. It's a race-condition by its very nature. If you depend on the code inside the callback to be executed before the next interval, use a recursive setTimeout
instead.
Also, unless your interval is called lockUpBrowser
, that duration between callbacks is likely much too short for realistic performance handling.
(function myRecursiveTask() {
// Do your task here
myTask();
if (!someConditionToAllowABailOut) {
setTimeout(myRecursiveTask, 100); // 100ms loop
}
}());
Upvotes: 8
Reputation: 71384
I would certainly question the need for such an approach. What are you needing to check for every 1ms that you can't check for every 10ms, 100ms, or every second?
Are you 100% certain that the check functionality that you will run every will always execute in < 1ms such that you don't have multiple check processes stacking up to run.
How much memory and CPU does the process take, and are you going to potentially slow down the user's browser to the point where simply actions like scrolling become painful for the user?
Upvotes: 1
Reputation: 179086
Yes, if the function reference passed to setInterval
takes longer to execute than the interval, calls to the function will queue and bog down the browser. If you're trying to perform an animation and want to change each step as fast as possible, there is a requestAnimationFrame
function that should be used for modern browsers. Personally, I've never needed to perform a function faster than every 15ms
.
Upvotes: 1
Reputation: 46008
setInterval
is not guaranteed to execute at precisely the interval specified.
It will execute as soon as possible, but since javasript is single-threaded and some other code may execute at this time your callback may be delayed.
If you're using setInterval
with 1ms than you're probably trying to solve your problem in a wrong way.
Upvotes: 4