I’m working on a website mainly for mobile and tablet.
I just want to ask is there any drawback on using a bit too much Interval?
As for now i’m using 1 interval with 5000ms to get and check current time and 1 interval with 100ms to check if the device’s width change (for responsive purpose)
I’ve heard my senior said that we should try to use those interval as less as possible, it may cause some hole and lag and such. Is it true?
Update:
Check this page, and all linked articles of interest: Web Workers, Asynchronous events and Timeout in particular
The main disadvantage when using intervals is down to the fact that all current JS implementations that I know of are single threaded. So if you set an interval to call a function every 100ms, and another every 500ms, the intervals won’t be executed simultaneously. If you rely heavily on the first interval having returned in the code you execute with the second interval, you’re going to run into trouble sooner or later.
Another thing you might notice is that the intervals are not very accurate. 100ms should be seen as ~100ms, and make no mistake the difference between the set interval and the actual interval can be quite big (an interval of 100ms can turn out to be as much as 150ms easily).
Bottom line, your chief is right, avoid as much as possible. However, sometimes there is no alternative but to use intervals. In which case, List all intervals, find the smallest common denominator and set one big interval that uses a closure to call the various functions when “their time has come”
You can expand this to return an object that allows you to set extra intervals, change the main interval time, unset certain intervals etc…
Edit
I overlooked the fact that you’re using an interval. That’s just not necessary:
window.onresizeorwindow.addEventListener('resize',handlerFunction,false);will do just that. Behind the scenes, JS has an event cycle/loop that takes care of things much more efficiently than any kind of self-made code.It’s often said that the best developers are, in essence, lazy people: They’ll go through a lot of trouble, just to be sure that what they need hasn’t been done before. If they find out about something that does what they need, they’ll use that, rather than writing the same thing themselves.
Anyway, I’ve added a link on the very top of my answer, and I’m going to add it here a second time. Check it out, especially the references to web workers, which might prove useful if you’re checking the time (not sure how/why/what you’re doing there).