Is Javascript setInterval a resource loop?

I am developing an application to run on a very low spec machine .. and I need it to be as efficient as possible.

I needed to emit about 10 intervals per second, which just makes an ajax call .. and then does some add / remove classes and (think of it like a SERVER status monitor)

I know that in FLASH (oh the good old days, flashes) that have a lot of intervals can cause processor bursts. So I am very conservative with the release of setIntervals in AS 2.0 earlier.

I was wondering if this is the same case with JS? or is it ok for JS to have a bunch of spacing (which makes easy tasks) work? I noticed many sites do this, even facebook has a lot of spacing, script uploads, etc.

And oh, in one interval, I wanted to run it for 50ms (it loads as a status.php link) ... is this ok?

Maybe I could optimize my interval calls, no problem, but I'm just wondering how "heavy" or "light" background intervals are in JS ..

Thanks everyone

+3


source to share


3 answers


10 intervals every second means calling every 100ms shouldn't be a problem in my opinion, but if you ask me I would call a call every 250ms . Between the two what the user will notice.



Also make sure there is a mechanism to handle a long response from the server in case of delay and stop interval if there is a drag.

+3


source


Be that as it may, I prefer setTimeout

more setInterval

- to what I don't use at all setInterval

.

The problem you will run into is that if one process takes longer than it needs to, let me present you with an imaginary situation:

window.setInterval(takes100msToRun, 50);
window.setInterval(takes50msToRun, 50);
window.setInterval(takes20msToRun, 50);

      

The problem is that the first interval will take longer than necessary, so now there will be two requests in two intervals, and the browser will try to catch up with them by executing them as quickly as possible. The second interval takes 50ms, so it still works when the third interval arrives.



This creates an ugly situation that can lead to a lot of drag.

On the other hand, if you set Timeout, then you are not saying, "Run this every 50ms", but rather "Run another one of those 50ms from the end." (Assuming, of course, that the functions set a different setTimeout to re-execute.)

This is absolute garbage for things that need good sync times, but beats everything else.

+2


source


setTimeout and setInterval will have little performance impact.

Since the browser has a lot of functions running / listening / running.

Even a small operation like moving the mouse to vote for this answer triggers thousands of events and dozens of functions are triggered.

Don't use setInterval. In fact, the library underline doesn't use it either.

See how they implement _.throttle without setInterval.

http://learningcn.com/underscore/docs/underscore.html#section-66

0


source







All Articles